【问题标题】:How can I mock multiple get axios request in Jest unit test for an async action that calls a few more async actions?如何在 Jest 单元测试中为调用更多异步操作的异步操作模拟多个 get axios 请求?
【发布时间】:2021-08-04 15:59:39
【问题描述】:

我正在使用 axios mock 在我的应用程序中测试 redux 操作。我坚持测试发送POST 请求的异步操作函数并调度更多发送自己的GET 请求的异步操作的问题。我如何使用模拟来管理它?

动作:

export function recordStepCompleted(step, isNewLevel = true) {
    return function (dispatch) {
        // setUserTaskComplete() action sends `POST` request
        dispatch(setUserTaskComplete(step))
            .then(() => isNewLevel && dispatch(rewardsActions.getUserLevels()));
        dispatch({
            type: types.RECORD_STEP_COMPLETED,
            payload: { step }
        });
    };
}
export function getUserLevels() {
    return function (dispatch, getState) {
        dispatch(getAchievements()) // it sends GET request
            .then(achievements => {
                dispatch({ type: types.GET_LEVELS.REQUEST });
                return api.getLevels() // it also sends GET request
                    .then(res => {
                        //......
                        dispatch({
                            type: types.GET_LEVELS.SUCCESS,
                            payload: { levels: { ...res.data, ... } }
                        });
                    })
                    .catch(error => /*....*/);
            });
    };
}

因此,总的来说,我需要模拟三个不同的请求来测试 recordStepCompleted 操作,但我不知道如何操作。请帮帮我。提前致谢!

【问题讨论】:

标签: reactjs unit-testing redux jestjs axios


【解决方案1】:

您可以扩展 AxiosStatic 接口来创建自己的接口并使用 jest.fn() 来 传递您的回复:

    import axios, { AxiosStatic } from "axios";
    jest.mock("axios");

    interface AxiosMock extends AxiosStatic {
    mockResolvedValue: (promise: Promise<Partial<AxiosResponse>>) => void;
    mockRejectedValue: (error: Partial<AxiosError>) => void;
    mockResolvedValueOnce: (promise: Promise<Partial<AxiosResponse>>) => this;
}

    const mockAxios = axios as AxiosMock;
    const myMock = jest.fn();
        myMock
            .mockReturnValueOnce({ "Your DATA 1" })
            .mockReturnValueOnce({ "Your DATA 2" })
            .mockReturnValueOnce({ "Your DATA 3" });

        mockAxios
            .mockResolvedValueOnce(Promise.resolve(myMock()))
            .mockResolvedValueOnce(Promise.resolve(myMock()))
            .mockResolvedValue(Promise.resolve(myMock()));

【讨论】:

    猜你喜欢
    • 2012-05-20
    • 2017-10-14
    • 2014-02-27
    • 1970-01-01
    • 2020-02-19
    • 1970-01-01
    • 2019-10-31
    相关资源
    最近更新 更多