Blog>
Snippets

Mocking API Calls in Saga

Show how to mock an API call within a saga using jest.mock, handling both success and error responses.
jest.mock('axios')
Firstly, we mock the axios module itself to intercept calls and provide custom responses.
const mockAxiosSuccess = { data: { todos: ['todo1', 'todo2'] } };
const mockAxiosError = new Error('An error occurred');
Define mock responses for success and error scenarios.
axios.get.mockImplementation(url => {
  if(url === 'http://example.com/todos') {
    return Promise.resolve(mockAxiosSuccess);
  } else {
    return Promise.reject(mockAxiosError);
  }
});
Conditionally resolve or reject axios.get calls based on the URL, simulating scenarios.
function* fetchTodosSaga() {
  try {
    const response = yield call(axios.get, 'http://example.com/todos');
    yield put({ type: 'FETCH_TODOS_SUCCESS', payload: response.data });
  } catch (error) {
    yield put({ type: 'FETCH_TODOS_FAILED', payload: error.message });
  }
}
Saga to fetch todos, handling both success by dispatching 'FETCH_TODOS_SUCCESS' and errors by dispatching 'FETCH_TODOS_FAILED'.
describe('fetchTodosSaga', () => {
  it('handles success', async () => {
    const dispatchedActions = [];
    const fakeStore = {
      getState: () => ({}),
      dispatch: action => dispatchedActions.push(action)
    };
    await runSaga(fakeStore, fetchTodosSaga).toPromise();
    expect(dispatchedActions).toContainEqual({ type: 'FETCH_TODOS_SUCCESS', payload: mockAxiosSuccess.data });
  });

  it('handles failure', async () => {
    const dispatchedActions = [];
    const fakeStore = {
      getState: () => ({}),
      dispatch: action => dispatchedActions.push(action)
    };
    axios.get.mockImplementationOnce(() => Promise.reject(mockAxiosError));
    await runSaga(fakeStore, fetchTodosSaga).toPromise();
    expect(dispatchedActions).toContainEqual({ type: 'FETCH_TODOS_FAILED', payload: mockAxiosError.message });
  });
})
Test cases for the fetchTodosSaga both for success and failure scenarios. We intercept the dispatched actions to verify the saga's behavior.