Blog>
Snippets

Testing Task Cancellation

Shows how to write test cases for saga tasks with cancellation logic, using Redux-Saga's testing utilities to simulate and assert the cancellation behavior.
import {fork, take, cancel} from 'redux-saga/effects';
import {createMockTask} from '@redux-saga/testing-utils';
import {expectSaga} from 'redux-saga-test-plan';
import {mySaga, myWorker} from './sagas'; // import your sagas

// Saga to be tested
function* mySaga() {
  const task = yield fork(myWorker);
  yield take('CANCEL_TASK');
  yield cancel(task);
}

// Worker saga
function* myWorker() {
  // Worker saga logic
}
Defines `mySaga` that forks `myWorker` and listens for a 'CANCEL_TASK' action to cancel the worker.
describe('Saga cancellation', () => {
  it('should cancel the worker task on CANCEL_TASK action', () => {
    const mockTask = createMockTask();

    return expectSaga(mySaga)
      .provide([
        [fork(myWorker), mockTask]
      ])
      .put({type: 'CANCEL_TASK'})
      .run();
  });
});
Tests `mySaga` to ensure it cancels `myWorker` upon receiving a 'CANCEL_TASK' action. Uses `expectSaga` from `redux-saga-test-plan` and `createMockTask` for mocking.