Blog>
Snippets

Integrating redux-saga-test-plan for Integrated Saga Testing

Illustrate the use of redux-saga-test-plan to run integrated tests on a saga, covering complex asynchronous flows and race conditions.
import { expectSaga } from 'redux-saga-test-plan';
import { call, put } from 'redux-saga/effects';
import { asyncAction, failureAction, successAction } from './actions';
import { fetchData } from './api';
import mySaga from './sagas';
This sets up the test, importing necessary functions and files. 'expectSaga' is from 'redux-saga-test-plan' for running our integrated tests. The 'call', and 'put' effects from 'redux-saga/effects' aid in describing the saga's step-by-step effects. Actions and the actual saga function are also imported.
it('handles the saga for successful data fetching', () => {
  return expectSaga(mySaga, asyncAction())
    .provide([
      [call(fetchData, 'url'), { data: 'test data' }]
    ])
    .put(successAction({ data: 'test data' }))
    .run();
});
This test simulates the scenario where data fetching is successful. The 'provide' method stubs out the 'call' effect to return mock data. The 'put' method expectation checks if the saga correctly dispatches a success action with the fetched data.
it('handles the saga for failed data fetching', () => {
  return expectSaga(mySaga, asyncAction())
    .provide([
      [call(fetchData, 'url'), Promise.reject(new Error('An error occurred'))]
    ])
    .put(failureAction(new Error('An error occurred')))
    .run();
});
This test covers the failure case for the data fetching saga. The 'provide' method is used to simulate an error during the fetch process. The expectation is that the saga dispatches the failure action correctly with the error.
it('handles race conditions between success and timeout in data fetching', () => {
  return expectSaga(mySaga, asyncAction())
    .provide([
      [call(fetchData, 'url'), { data: 'race win data' }]
    ])
    .put(successAction({ data: 'race win data' }))
    .not.put(failureAction())
    .run({ silenceTimeout: true });
});
In this test, a race condition is simulated to ensure the saga handles it correctly. Here, the data fetching call wins the race, resulting in the success action being dispatched. The 'not.put' assertion verifies that the failure action is not dispatched, which should be the case if the saga handles the race condition appropriately.