Blog>
Snippets

Verifying Yielded Effects in Order

Use redux-saga-test-plan to assert that a saga yields effects in the correct order, including calls, puts, and takes.
import { testSaga } from 'redux-saga-test-plan';
import { takeEvery, call, put } from 'redux-saga/effects';
import { fetchDataSuccess, FETCH_DATA_REQUEST } from './actions';
import { fetchData } from './api';

// Saga to test
function* fetchDataSaga(action) {
  try {
    const data = yield call(fetchData, action.payload);
    yield put(fetchDataSuccess(data));
  } catch (error) {
    // handle error
  }
}

// Example test
describe('fetchDataSaga', () => {
  it('yields effects in the correct order', () => {
    testSaga(fetchDataSaga, { type: FETCH_DATA_REQUEST, payload: 'testId' })
      .next()
      .call(fetchData, 'testId')
      .next('testData')
      .put(fetchDataSuccess('testData'))
      .next()
      .isDone();
  });
});
This code imports 'testSaga' from 'redux-saga-test-plan', along with relevant redux-saga effects and action creators from a hypothetical actions and api file. It defines a 'fetchDataSaga' that fetches data using a call effect and dispatches the result with a put effect. The test for 'fetchDataSaga' verifies that each yield in the saga happens in the correct order: first, it expects a call to fetchData with 'testId', then expects a put effect with the result of that call. The test advances through the saga using .next() and asserts the expected effects.