简体   繁体   中英

how can I test this redux action in jest?

I want to test this redux action which uses axios, I have succesfully tested the success path but I can't reach the catch block to complete the code coverage. I'm mocking axios using a mocks folder in jest.

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());
        });
};

this is my success path test which implements a redux store and expects loading and setTasks to run and the setTasks action to have a payload that matches my mockObjects tasks list.

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);
    });
});

I've tried to use this code to make the catch code to run but it executes the same code as the success path and sets the tasks list to undefined

 mockAxios.get.mockImplementationOnce(() => Promise.reject({ status: 400 }));

When testing frontend code that makes HTTP request, I suggest using a mocking library to create fake responses. Two that I am familar with are nock and fetch-mock . You should be able to throw an error in your mock response code so that it triggers the catch() branch.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM