Testing Redux Sagas with Jest
Present a basic example of how to test a Redux Saga using the Jest framework, including mocking effects and asserting that the saga yields the expected effects in order.
import { runSaga } from 'redux-saga';
import { call, put } from 'redux-saga/effects';
import { fetchUserData, apiGetUserData } from './sagas';
Imports necessary parts from redux-saga, as well as the saga (fetchUserData) and the API call (apiGetUserData) to be tested.
test('fetchUserData Saga test', async () => {
const dispatched = [];
await runSaga({
dispatch: (action) => dispatched.push(action),
getState: () => ({state: 'test'})
}, fetchUserData).toPromise();
// Your assertions come here
});
Defines a Jest test for the fetchUserData saga. It uses runSaga to run the saga outside of the Redux Middleware environment. Actions dispatched by the saga are captured in the 'dispatched' array.
const mockUserData = { userId: 1, name: 'Test User' };
test('fetchUserData success', async () => {
const requestUserData = jest.fn().mockImplementation(() => Promise.resolve(mockUserData));
const dispatched = [];
await runSaga({
dispatch: (action) => dispatched.push(action),
getState: () => ({})
}, fetchUserData, { apiCall: requestUserData }).toPromise();
expect(requestUserData).toHaveBeenCalled();
expect(dispatched).toContainEqual(put({ type: 'FETCH_SUCCESS', payload: mockUserData }));
});
Tests the success path of the fetchUserData saga. It mocks the API call to return predefined user data and asserts that the saga dispatches the correct success action.
test('fetchUserData failure', async () => {
const requestUserData = jest.fn().mockImplementation(() => Promise.reject(new Error('API error')));
const dispatched = [];
await runSaga({
dispatch: (action) => dispatched.push(action),
getState: () => ({})
}, fetchUserData, { apiCall: requestUserData }).toPromise();
expect(requestUserData).toHaveBeenCalled();
expect(dispatched).toContainEqual(put({ type: 'FETCH_FAILURE', error: 'API error' }));
});
Tests the failure path of the fetchUserData saga. It mocks the API call to simulate an API error and checks that the saga dispatches the correct failure action.