jfairbank / redux-saga-test-plan

Test Redux Saga with an easy plan.
http://redux-saga-test-plan.jeremyfairbank.com
MIT License
1.25k stars 127 forks source link

Question: How to set initial state for unit tests #239

Open arianacosta opened 5 years ago

arianacosta commented 5 years ago

Hello,

I've been trying to test that multiple PUT effects are being yielded by an ALL. The problem is that this saga uses select, but the default state for the application is empty. Therefore, mapping over an empty array produces no PUT effects.

My questios are:

a) How can I set the initial state for each unit test? b) Is there a better or easier way of testing this?

Initial state that I'm trying to set before the test:

{
    panels: ['panelA', 'panelB],
}

Saga:

export function* reloadPanels() {
    const panels = yield select(state => state.panels); // panels should be an array of N strings

    const actions = _.map(panels, panel => put({
      type: FETCH_PANEL,
      payload: {
        panel,
      },
    }));

    yield all(actions); // it should handle N PUT effects
}

Unit test:

it('should dispatch multiple fetch panels', () => {
    testSaga(reloadPanels)
      .next()
      .select() // <- How to set the initial state before this select?

      .next()
      .all([
        put({
          type: FETCH_PANEL,
          payload: { 
            panel: 'panelA', 
          },
        }),
        put({
          type: FETCH_PANEL,
          payload: { 
            panel: 'panelB', 
          },
        }),
      ])

      .next()
      .isDone();
  });
otroboe commented 5 years ago

@arianacosta Hey! I'm wondering the same thing, did you find a workaround afterall ?

otroboe commented 5 years ago

@arianacosta I found it, you have to pass the mocked data in the next() method after your select().

So for you case, it should be something like that.

it('should dispatch multiple fetch panels', () => {
    testSaga(reloadPanels)
        .next()
        .select()
        .next(['panelA', 'panelB'])
        .all([
            put({
                type: FETCH_PANEL,
                payload: {
                    panel: 'panelA',
                },
            }),
            put({
                type: FETCH_PANEL,
                payload: {
                    panel: 'panelB',
                },
            }),
        ])
        .next()
        .isDone();
});