Blog>
Snippets

Testing a Saga

Show how to test a saga with an API call using the `redux-saga-test-plan`, focusing on mocking responses and verifying saga execution flow.
import { expectSaga } from 'redux-saga-test-plan';
import { call } from 'redux-saga/effects';
import { fetchUserApi } from './api';
import { getUserSaga } from './sagas';
import { getUserSuccess, getUserFailure } from './actions';
First, import necessary functions and constants. This includes the saga and action creators you want to test, as well as redux-saga-test-plan's expectSaga, and redux-saga's call effect.
const mockUser = { id: 1, name: 'John Doe' };
Define a mock response that simulates the data you would expect to receive from the API call.
it('handles successful API call', () => {
  return expectSaga(getUserSaga, { type: 'GET_USER_REQUEST', userId: 1 })
    .provide([[call(fetchUserApi, 1), mockUser]])
    .put(getUserSuccess(mockUser))
    .run();
});
Write a test for a successful API call. Use 'provide' to mock the API call's response. Use 'put' to assert that the saga will eventually dispatch the getUserSuccess action with the mockUser data.
it('handles failed API call', () => {
  const error = new Error('404 Not Found');
  return expectSaga(getUserSaga, { type: 'GET_USER_REQUEST', userId: 2 })
    .provide([[call(fetchUserApi, 2), Promise.reject(error)]])
    .put(getUserFailure(error))
    .run();
});
Write another test for when the API call fails. By providing a rejected promise, you simulate an API call failure and then assert that the saga will dispatch the getUserFailure action with the error.