Blog>
Snippets

Unit Testing a Saga with Jest

Showcase a code example testing a Redux-Saga function with Jest, including mocking the API call and asserting the Saga's behavior.
import { runSaga } from 'redux-saga';
import { call, put } from 'redux-saga/effects';
import { fetchUserData, userDataFetchedSuccessfully, fetchFailed } from './actions';
import { getUserDataSaga } from './sagas';
import * as api from './api';
This code snippet imports necessary functions and variables. It includes the saga to be tested (`getUserDataSaga`), actions it dispatches, and the API method it calls.
// Mock the API call
jest.mock('./api', () => ({
  fetchUserData: jest.fn()
}));
Mock the API module and the specific call within the saga that needs to be intercepted. This prevents the actual API call during testing.
// Test success path
test('should fetch user data successfully', async () => {
  const dispatched = [];
  const fakeUserData = { name: 'John Doe', age: 30 };

  api.fetchUserData.mockResolvedValue(fakeUserData);

  await runSaga({
    dispatch: (action) => dispatched.push(action)
  }, getUserDataSaga).toPromise();

  expect(api.fetchUserData).toHaveBeenCalledTimes(1);
  expect(dispatched).toContainEqual(userDataFetchedSuccessfully(fakeUserData));
});
Test the successful execution path of the saga. It checks if the correct action is dispatched with the expected data when the API call resolves successfully.
// Test failure path
test('should handle user data fetch error', async () => {
  const dispatched = [];

  api.fetchUserData.mockRejectedValue(new Error('API call failed'));

  await runSaga({
    dispatch: (action) => dispatched.push(action)
  }, getUserDataSaga).toPromise();

  expect(api.fetchUserData).toHaveBeenCalledTimes(1);
  expect(dispatched).toContainEqual(fetchFailed());
});
Test the failure execution path of the saga. It verifies that the saga correctly dispatches an error action when the API call fails.