相关疑难解决方法(0)

Typescript和Jest:避免模拟函数的类型错误

当想要使用Jest模拟外部模块时,我们可以使用该jest.mock()方法自动模拟模块上的函数.

然后,我们可以按照我们的意愿操纵和查询模拟模块上的模拟函数.

例如,考虑以下用于模拟axios模块的设计示例:

import myModuleThatCallsAxios from '../myModule';
import axios from 'axios';

jest.mock('axios');

it('Calls the GET method as expected', async () => {
  const expectedResult: string = 'result';

  axios.get.mockReturnValueOnce({ data: expectedResult });
  const result = await myModuleThatCallsAxios.makeGetRequest();

  expect(axios.get).toHaveBeenCalled();
  expect(result).toBe(expectedResult);
});
Run Code Online (Sandbox Code Playgroud)

以上将在Jest中正常运行,但会抛出一个Typescript错误:

属性'mockReturnValueOnce'在类型'(url:string,config?:AxiosRequestConfig | undefined)=> AxiosPromise'上不存在.

typedef axios.get正确不包含mockReturnValueOnce属性.我们可以强制将Typescript axios.get包装为Object文字Object(axios.get),但是:

在保持类型安全的同时模拟功能的惯用方法是什么?

mocking node.js typescript reactjs jestjs

15
推荐指数
6
解决办法
9939
查看次数

如何使用笑话和反应测试库测试调用提交表单的按钮

所以我试图测试 onSubmit 函数是否在单击按钮时被触发 - 我这样做的方式是通过测试 onSubmit 函数的内部正在获取调用(axios post 方法)

考试

describe('RecipeSearch', () => {
    test('submit button should return post function to recipes/search/', () => {
        let mock = new MockAdapter(axios);
        userEvent.selectOptions(screen.getByRole('combobox'), 'Sweet');
        userEvent.click(screen.getByText('Search'));

        const config = {
            headers: {
                'Content-Type': 'application/json',
            },
        };
        const searchRecipes = mock.onPost(
            `${process.env.REACT_APP_API_URL}/recipes/search/`,
            { flavor_type: 'Sweet' },
            { config }
        );
        expect(searchRecipes).toHaveBeenCalled();
    });
});

Run Code Online (Sandbox Code Playgroud)

错误

    expect(received).toHaveBeenCalled()

    Matcher error: received value must be a mock or spy function

    Received has type:  object
    Received has value: {"abortRequest": …
Run Code Online (Sandbox Code Playgroud)

testing reactjs jestjs react-testing-library

7
推荐指数
1
解决办法
3万
查看次数

为什么TypeError:axios.create不是函数?测试axios GET时

我正在尝试在React中测试我的axios API函数。

在这里发现了这个问题:我如何在笑话测试axios,它指向使用axios-mock-adapter

import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import chatbot from './chatbot';

describe('Chatbot', () => {
    it('returns data when sendMessage is called', done => {
        var mock = new MockAdapter(axios);
        const data = { response: true };
        mock.onGet('https://us-central1-hutoma-backend.cloudfunctions.net/chat').reply(200, data);

        chatbot.sendMessage(0, 'any').then(response => {
            expect(response).toEqual(data);
            done();
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

真正的功能:

/**
 * Retrieve all Akamai images
 * @param  {String} akamai Akamai url
 * @return {Thenable}      Resolved: Akamai images
 */
export const callGetAkamai = …
Run Code Online (Sandbox Code Playgroud)

testing unit-testing axios axios-mock-adapter

6
推荐指数
2
解决办法
3938
查看次数

使用 jest.mock('axios') 时如何模拟拦截器?

使用 jest 运行测试时,我有基本的测试服语法:

jest.mock('axios');

describe('app', () => {
    let render

    beforeEach(() => {
        axiosMock.get.mockResolvedValueOnce({
            data: {greeting: 'hello there'},
        }),
        render= renderApp()
    });

    test('should render something', () => {
        expect(something).toBeInTheDocument();
    });


});
Run Code Online (Sandbox Code Playgroud)

问题是我的代码中有拦截器,当使用 jest 命令输出运行测试时:

类型错误:无法读取未定义的属性“拦截器”

并指向拦截器对象

axiosInstance.interceptors.request.use(...

axiosInstance 是存储返回的变量 axios.create

export const axiosInstance = axios.create({...

在 SO How do I test axios in jest上参考了这个 axios 线程,但它不涉及任何拦截器,所以并没有真正的帮助。

reactjs jestjs axios react-testing-library

6
推荐指数
3
解决办法
1万
查看次数

Axios 连接不允许 Jest 被终止

我是 Node/Jest 世界的新手。我正在尝试测试以下功能:

\n
export async function visitPage(url: string) {\n    const cookie =  ''\n    let headers = {\n    'authority': 'www.example.com',\n    'pragma': 'no-cache',\n    'cache-control': 'no-cache',\n    'upgrade-insecure-requests': '1',\n    'dnt': '1',\n    'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36',\n    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',\n    'sec-fetch-site': 'same-origin',\n    'sec-fetch-mode': 'navigate',\n    'sec-fetch-user': '?1',\n    'sec-fetch-dest': 'document',\n    'rtt': '350',\n    'downlink': '1.45',\n    'ect': '3g',\n    'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="96", "Google Chrome";v="96"',\n    'sec-ch-ua-mobile': '?0',\n    'sec-ch-ua-platform': '"macOS"',\n    'referer': 'https://google.com',\n    'accept-language': 'en-US,en;q=0.9,ur;q=0.8,zh-CN;q=0.7,zh;q=0.6',    \n    'Accept-Encoding': 'gzip',\n    'cookie': cookie,\n\n    }\n\n    try …
Run Code Online (Sandbox Code Playgroud)

node.js typescript jestjs axios

5
推荐指数
1
解决办法
696
查看次数

如何为 Axios 和 Hooks 实现 Jest 测试 - useEffect

如何在 React 的 useEffect 中为 Axios 调用编写 Jest 测试?

我在这里找到了如何模拟 Axios - /sf/answers/3615829941/

我还知道如何触发 useEffect 如果它是由用户交互(例如单击按钮)调用的。但是在下面的情况下,useEffect 被一个异步函数调用,该函数由 Axios 的响应触发。

例子:

成分

import React, { useState, useEffect } from "react";
import axios from "axios";

const LoadImage = () => {
  const [loading, setLoading] = useState(true);
  const [data, setData] = useState(null);

  const fetchData = async () => {
    return await axios
      .get("https://picsum.photos/200/300.jpg", {
        "Content-Type": "application/xml; charset=utf-8",
      })
      .then((response) => {
        setData(response.config.url);
        setLoading(false);
      })
      .catch((error) => {
        console.log(error);
      });
  };

  useEffect(() => { …
Run Code Online (Sandbox Code Playgroud)

reactjs jestjs axios use-effect

3
推荐指数
1
解决办法
3851
查看次数

测试时,导致 React 状态更新的代码应该包装到 act(...) 中 - 使用简单的 React-native 嵌套屏幕/组件和 jest axios

我是单元测试/玩笑的新手,但我了解一些有关 React Native 的知识。我想为我的主屏幕编写一个测试,其中包含一个发出简单请求的组件。代码运行没有任何问题,但当我用 Jest 运行它时失败。

主屏.js

import { View } from 'react-native'
import APIExample from '@components/Examples/APIExample'
const HomeScreen = () => {
    return (<View> <APIExample /> </View>)
}
export default HomeScreen
Run Code Online (Sandbox Code Playgroud)

HomeScreen.test.js

import { render } from '@testing-library/react-native'
import HomeScreen from '@screens/HomeScreen'

it('should run', async () => {
    const { getByText } = await render(<HomeScreen />)
})
Run Code Online (Sandbox Code Playgroud)

APIExample.js

import { useState, useEffect } from 'react'
import { Text, View } from 'react-native'
import API from '../../API'

const APIExample = …
Run Code Online (Sandbox Code Playgroud)

reactjs jestjs react-native testing-libraryreact-native

2
推荐指数
1
解决办法
2049
查看次数