Blog>
Snippets

Testing a Full Saga Execution with Redux-saga-test-plan

Demonstrate using redux-saga-test-plan to test a full saga execution, including how to assert the final state after all effects have been executed.
import { expectSaga } from 'redux-saga-test-plan';
import { put, call } from 'redux-saga/effects';
import { fetchUserData, userDataFetched, fetchUserDataFailed } from './actions';
import { getUserData } from './api';
import userSaga from './userSaga';
Imports for testing a saga. This includes the expectSaga function from redux-saga-test-plan, the necessary saga effect creators (put, call), the action creators from the saga's module, the API call function, and the saga itself.
function* userSaga(action) {
  try {
    const data = yield call(getUserData, action.userId);
    yield put(userDataFetched(data));
  } catch (e) {
    yield put(fetchUserDataFailed(e.message));
  }
}
Definition of a sample userSaga that fetches user data. This saga attempts to load user data using getUserData and dispatches userDataFetched on success or fetchUserDataFailed on failure.
test('full saga execution with redux-saga-test-plan', () => {
  return expectSaga(userSaga, fetchUserData(1))
    // Mock the API call to return specific data
    .provide([[call(getUserData, 1), Promise.resolve('User data')]])
    // Assert that the saga will eventually put userDataFetched action
    .put(userDataFetched('User data'))
    // Run the saga to the end
    .run();
});
Test case using redux-saga-test-plan's expectSaga to run a full saga execution. This test checks if the saga performs as expected when the API call is successful. .provide is used to mock the getUserData call, and .put asserts the final action dispatched by the saga.