Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon How can I use Jest to simulate error responses in Redux actions


How can I use Jest to simulate error responses in Redux actions


To test the error handling in your Redux thunk actions using Jest, you can mock the `fetchHelper` function and simulate different response scenarios. Here's an example of how you can do it:

javascript
// __tests__/actions.test.js
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import * as actions from '../actions';
import * as fetchHelper from '../fetchHelper';

const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);

jest.mock('../fetchHelper');

describe('async actions', () => {
  afterEach(() => {
    jest.clearAllMocks();
  });

  it('creates SET_LOADING and SET_DATA actions on successful fetch', () => {
    const mockResponse = { data: 'some data' };
    fetchHelper.fetchHelper.mockResolvedValue(mockResponse);

    const expectedActions = [
      { type: 'SET_LOADING', payload: true },
      { type: 'SET_DATA', payload: mockResponse.data },
    ];

    const store = mockStore({});
    return store.dispatch(actions.getSomeData()).then(() => {
      expect(store.getActions()).toEqual(expectedActions);
    });
  });

  it('creates SET_LOADING and SET_ERROR actions on failed fetch', () => {
    const mockError = new Error('Network Error');
    fetchHelper.fetchHelper.mockRejectedValue(mockError);

    const expectedActions = [
      { type: 'SET_LOADING', payload: true },
      { type: 'SET_ERROR', payload: mockError },
    ];

    const store = mockStore({});
    return store.dispatch(actions.getSomeData()).then(
      () => {
        // This should not happen
        expect(true).toBe(false);
      },
      (error) => {
        expect(store.getActions()).toEqual(expectedActions);
        expect(error).toEqual(mockError);
      }
    );
  });
});

In this example, we're using the `redux-mock-store` library to create a mock Redux store, and the `thunk` middleware to handle the asynchronous actions. We're also mocking the `fetchHelper` module using `jest.mock('../fetchHelper')`.

In the first test case, we're simulating a successful fetch by mocking the `fetchHelper.fetchHelper` function to resolve with a mock response. We then check if the expected actions (setting the loading state and setting the data) are dispatched.

In the second test case, we're simulating a failed fetch by mocking the `fetchHelper.fetchHelper` function to reject with a mock error. We then check if the expected actions (setting the loading state and setting the error) are dispatched, and that the error is correctly propagated.

By mocking the `fetchHelper` module, we can easily control the response scenarios and test the error handling in our Redux thunk actions.

Citations:
[1] https://blog.ldtalentwork.com/2020/04/09/how-to-test-asynchronous-redux-actions-using-jest/
[2] https://javascript.plainenglish.io/testing-async-redux-actions-with-jest-3bde5dd88607?gi=5e6e4c5a777f
[3] https://ximedes.com/blog/2017-02-03/test-redux-action-creators-with-jest
[4] https://www.callstack.com/blog/testing-react-native-with-the-new-jest-part-2-redux-snapshots-for-your-actions-and-reducers
[5] https://stackoverflow.com/questions/48172819/testing-dispatched-actions-in-redux-thunk-with-jest