【发布时间】:2019-11-13 18:02:38
【问题描述】:
我想测试这个使用 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 存储并期望加载和 setTasks 运行,并且 setTasks 操作具有与我的 mockObjects 任务列表匹配的有效负载。
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 代码运行,但它执行与成功路径相同的代码并将任务列表设置为未定义
mockAxios.get.mockImplementationOnce(() => Promise.reject({ status: 400 }));
【问题讨论】:
-
你可以使用axios-mock-adapter 之类的东西,而不是手动尝试模拟 Axios。
标签: javascript unit-testing redux jestjs axios