Search code examples
javascriptreduxredux-sagareact-boilerplate

How to test Saga that uses data from a dispatched action


I'm using redux-saga and testing using expect. Based on the example given in the (amazing) React Boilerplate, testing a saga that gets the data it needs from the Store (using a selector) is no problem.

However, some of my sagas rely on data included in the dispatched action:

export function* startSaga() {
  while (true) {
    const startAction = yield take(START);
    const id = startAction.id || false;
    ...

To test this, I am importing the saga and then calling it:

import { startSaga } from '../sagas.js';
startGenerator = startSaga();
...

Because of this there is no action kicking the saga off, and so the value of id is always going to be false.

My actions and reducers are tested separately: when testing sagas in a standalone fashion like this, is there a simple way to get this to work?


Solution

  • When running a saga generator function, you are in control of the data that gets passed back on every yield:

    import { startSaga } from '../sagas.js';
    let startGenerator = startSaga();
    
    let takeEffect = startGenerator.next()
    expect(takeEffect).toEqual(take(START));
    startGenerator.next({id: 234});