我如何才能开玩笑地测试这个redux动作?

我想测试使用axios的redux动作,我已经成功测试了成功路径,但是我无法到达catch块来完成代码覆盖。我在开玩笑地使用 mocks 文件夹嘲笑axios。

export const fetchTasks = () => dispatch => {
    dispatch(fetchLoading());
    axios
        .get(url + '/all',{ mode: 'cors' })
        .then(response => {
            dispatch(setTasks(response.data));
            dispatch(fetchDone());
        })
        .catch(response => {
            console.log(response);
            dispatch(fetchDone());
        });
};

这是我的成功路径测试,该测试实现了一个redux存储,并期望运行load和setTasks以及setTasks操作具有与我的模拟对象任务列表匹配的有效负载。

describe('when fetchTasks is dispatched',() => {
    it('should dispatch other actions with correct payloads',async () => {
        const store = testStore();
        const spyOnDispatch = jest.spyOn(store,'dispatch');
        await tasksactions.fetchTasks()(store.dispatch,store.getState);
        expect(spyOnDispatch).toHaveBeenCalledWith({ type: 'FETCH_LOADING' });
        expect(spyOnDispatch).toHaveBeenCalledWith({ type: 'SET_TASKS',tasks: mockObjects.mockTasks });
        expect(spyOnDispatch).toHaveBeenCalledWith({ type: 'FETCH_DONE' });
        expect(store.getState().tasksState.tasks).toEqual(mockObjects.mockTasks);
    });
});

我尝试使用此代码使catch代码运行,但它执行的代码与成功路径相同,并将任务列表设置为undefined

 mockAxios.get.mockImplementationOnce(() => Promise.reject({ status: 400 }));
heiseseo 回答:我如何才能开玩笑地测试这个redux动作?

在测试发出HTTP请求的前端代码时,建议使用模拟库来创建假响应。我熟悉的两个是nockfetch-mock。您应该能够在模拟响应代码中引发错误,从而触发catch()分支。

本文链接:https://www.f2er.com/3107800.html

大家都在问