Search code examples
unit-testingredux-sagaredux-saga-test-plan

Testing redux-saga takeEvery


I have the following super simple Redux-Saga that I want to test with Jest.

function* nextApi() {
  yield* takeEvery(
    (action) => !!(action.meta && action.meta.next),
    nextApiSaga
  )
}

I've looked at Redux-Sagas-Test-Plan, but that only seems to allow you to unit test functions that contain Saga Effect Creators and doesn't seem to support Saga Helpers. There is also Redux-Saga-Test but that just does a deepEqual on the yielded effect and doesn't test the arrow function.

What I want to be able to do is past the following two objects to takeEvery and see that nextApiSaga is only called in the second case.

{ type: 'foo' }

{ type: 'foo', meta: { next: 'bar' } }  

Solution

  • I left you a comment about redux-saga-test-plan having methods for saga helpers, but you can easily test takeEvery with it. Call testSaga with your saga and then invoke the takeEvery method assertion with the pattern (note I keep a reference to your original anonymous function) and the other saga.

    const helper = action => !!(action.meta && action.meta.next)
    
    function* nextApi() {
      yield* takeEvery(
        helper,
        nextApiSaga
      )
    }
    
    testSaga(nextApi).takeEvery(helper, nextApiSaga)