Blog>
Snippets

Mocking API Calls in Saga Tests

Demonstrate how to mock API calls in saga tests using redux-saga-test-plan to ensure sagas handle responses and errors correctly.
import { call, put } from 'redux-saga/effects';
import { expectSaga } from 'redux-saga-test-plan';
import { fetchUser } from './saga';
import * as api from './api';

// Mock API response
const user = { id: 1, name: 'John Doe' };
This setup code imports necessary functions and mocks the API response for a user fetch request.
it('fetches user successfully', () => {
  return expectSaga(fetchUser, { userId: 1 })
    .provide([[call(api.getUser, 1), user]])
    .put({ type: 'FETCH_USER_SUCCESS', user })
    .run();
});
This test simulates a successful API call by providing a mocked response to the `getUser` API call, and then asserts that the saga puts the expected success action.
it('handles fetch error', () => {
  const error = new Error('User not found');

  return expectSaga(fetchUser, { userId: 2 })
    .provide([[call(api.getUser, 2), throwError(error)]])
    .put({ type: 'FETCH_USER_FAILURE', error })
    .run();
});
This test simulates a failed API call by providing a mocked error response to the `getUser` API call, and then asserts that the saga puts the expected failure action.