Blog>
Snippets

Testing a Simple Fetch Saga

Show how to use redux-saga-test-plan to test a saga that performs a fetch request and dispatches an action with the result.
import { call, put } from 'redux-saga/effects';
import { expectSaga } from 'redux-saga-test-plan';
import { fetchUserData, userDataFetched } from './actions';
import { fetchUserSaga } from './sagas';
import * as api from './api';
First, we import necessary dependencies. This includes effects from redux-saga, testing utilities from redux-saga-test-plan, our actions, the saga we're testing, and the API simulation.
it('fetches user data successfully', () => {
  const user = { id: 1, name: 'John Doe' };
  return expectSaga(fetchUserSaga, fetchUserData(1))
    .provide([[call(api.fetchUser, 1), user]])
    .put(userDataFetched(user))
    .run();
});
The test simulates fetching user data. We use expectSaga to test the saga directly. With .provide(), we mock the API call, returning our test user. .put() asserts that the saga will eventually dispatch the userDataFetched action with the fetched user. Finally, .run() executes the test.