Home > Software engineering >  Jest test doesnt wait for a saga to end
Jest test doesnt wait for a saga to end

Time:04-14

Jest for testing, Redux-Saga

Let's say I have this saga:

export function* callCreateTemplate({payload}){
try{
  ...
  yield delay(1500)
  ...
}

Don't judge me for having this delay(1500) is related to the API.

Then, I have my test case in Jest where I call the saga with runSaga:

it('...'), async () => {
   ...
   await runSaga(...);
   expect(dispatchedActions).toHaveLength(3);
}

dispatchedActions is part of the mock and is an array with all the dispatched actions that the saga executes.

The thing is that, when I delete the delay(1500) inside the saga, the test case works fine, but when I execute the test with the delay(1500) the dispatched actions after the delay don't execute.

How can I make the test case to wait for the execution of the saga?

CodePudding user response:

runSaga returns a Task object which has a task.toPromise() method. You should convert the task to promise so that you can use async/await to wait for the completion of the task.

Besides, you need to make sure the value of timeout argument for the test case is greater than the milliseconds passed in the delay effect.

import { runSaga } from 'redux-saga';
import { delay, put } from 'redux-saga/effects';

export function* callCreateTemplate({ payload }) {
  yield delay(1500);
  yield put({ type: 'CREATE_TEMPLATE', payload });
}

describe('callCreateTemplate', () => {
  test('should pass', async () => {
    const dispatchedActions: any[] = [];
    await runSaga(
      {
        dispatch: (action) => dispatchedActions.push(action),
        getState: () => ({}),
      },
      callCreateTemplate,
      { payload: 'fake payload' },
    ).toPromise();
    expect(dispatchedActions).toHaveLength(1);
    expect(dispatchedActions).toEqual([{ type: 'CREATE_TEMPLATE', payload: 'fake payload' }]);
  }, 2000);
});

Test result:

 PASS   redux-saga-examples  packages/redux-saga-examples/src/stackoverflow/71787549/index.test.ts
  callCreateTemplate
    ✓ should pass (1508 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        4.118 s
  • Related