【问题标题】:How to mock axios in React with using axios.create function如何使用 axios.create 函数在 React 中模拟 axios
【发布时间】:2021-07-28 23:26:36
【问题描述】:

我正在使用 axios 处理 http 请求的 React 项目。我有一个带有 axios 配置的单独文件,如下所示:

import axios from 'axios'

export default axios.create({
    baseURL: " http://localhost:3001",
    params: {
    }
})

我在下面这样的 thunk 创作者中使用它:

import streams from "../apis/streams";
export const fetchStreams = () => {
    return async(dispatch: ThunkDispatch<void, State, Action>)  => {
        const response: AxiosResponse<Stream[]> = await streams.get<Stream[]>('/streams');
        dispatch({type: ActionType.FETCH_STREAMS, payload: response.data});
    }
} 

首先我创建了“src/__mocks__/axios.ts”文件,例如:

const mockedAxios: any = jest.createMockFromModule('axios');

mockedAxios.create = jest.fn(() => mockedAxios);

export default mockedAxios; 

然后我写了如下测试:

import mockedAxios, {AxiosResponse} from "axios";
import streamsApi from '../apis/streams'
import expectedStreams from "../mocks/expectedStreams";
jest.mock('axios')

describe('fetchStreams action', () => {

    it('Store is updated correctly', async () => {
        const mockedResponse: AxiosResponse = {
            data: expectedStreams,
            status: 200,
            statusText: 'OK',
            headers: {},
            config: {}
        }
        mockedAxios.get.mockImplementationOnce(() => {
            Promise.resolve(mockedResponse);
        })
        const results = await streamsApi.get('/streams');
        expect(results.data).toBe(mockedResponse.data);
    });
});

很遗憾,我收到了这样的错误:

这是为什么呢?在这种情况下,如何正确创建 fake API 响应? 我将不胜感激。

【问题讨论】:

    标签: reactjs typescript unit-testing axios jestjs


    【解决方案1】:

    好的,我知道出了什么问题。我忘记在 Promise 之前添加 return 像这样:

    mockedAxios.get.mockImplementationOnce(() => {
                return Promise.resolve(mockedResponse);
            })
    

    【讨论】:

      猜你喜欢
      • 2019-07-22
      • 2020-05-26
      • 2018-12-25
      • 2022-12-30
      • 2019-10-30
      • 2021-02-22
      • 2021-01-03
      • 1970-01-01
      相关资源
      最近更新 更多