Unit Testing a Redux-Saga with Jest
Provide an example of how to write a unit test for a Redux-Saga using Jest, focusing on testing the saga's behavior when an action is dispatched and ensuring it calls the expected effects.
import { runSaga } from 'redux-saga';
import { fetchUserDataSaga } from './sagas';
import * as api from './api';
// Mocking the api call
jest.mock('./api', () => ({
fetchUserData: jest.fn()
}));
Setup for the unit test, including importing necessary functions and mocking the API call using Jest. This is to isolate the saga's behavior from external dependencies.
describe('fetchUserDataSaga', () => {
it('calls the API and dispatches success action upon successful API call', async () => {
const dispatched = [];
const fakeUser = { id: 1, name: 'John Doe' };
api.fetchUserData.mockResolvedValue(fakeUser);
await runSaga({
dispatch: (action) => dispatched.push(action)
}, fetchUserDataSaga, { type: 'FETCH_USER_REQUEST' }).toPromise();
expect(api.fetchUserData).toHaveBeenCalledTimes(1);
expect(dispatched).toContainEqual({ type: 'FETCH_USER_SUCCESS', user: fakeUser });
});
});
The unit test itself, using Jest's describe and it functions to structure the test. This test checks if the saga calls the mock API and then dispatches the expected success action when the API call succeeds.