Skip to content

Instantly share code, notes, and snippets.

@jimbol
Last active November 16, 2016 15:21
Show Gist options
  • Save jimbol/299345e087dafb6090524f79f2c148ef to your computer and use it in GitHub Desktop.
Save jimbol/299345e087dafb6090524f79f2c148ef to your computer and use it in GitHub Desktop.
Redux-Saga Effect Runner

Testing with Effect Runner

A Redux-Saga test runner for Mocha

Goals

  • Switching the order of instructions should be easy
  • Associate instructions with their results
  • Changing instruction results should be easy

Guide

Step By Step

Define Effect

Lets start with a basic effect.

export function* getFoos(action) {
  const token = yield select(getToken);
  const response = yield call(fetchFoos, action.bars, token);
  yield put(handleResponse(response));
}

Example runner

In our mocha tests, we can stub a run like so. Its good to see it all together up front.

let action = {};
let token = 'abc-123';
const response = {};

beforeEach(() => {
  run = effectRunner(getFoos)
    .next('init', action)
    .next('getToken', token)
    .next('fetchFoos', response)
    .next('finish')
    .run();
});

Init Effect Runner

First we pass the effect into the runner

effectRunner(getFoos)

Invoking Effect

The first step after invoking effectRunner represents the invocation of the effect itself.

effectRunner(getFoos)
  .next('init', action)

This is like calling getFoos(action).

Defining Steps

After that we define each step, giving each a name and result (if needed).

runner.next('getToken', token)

The last step will be the final yield.

runner.next('finish');

Running the Runner

Once you are ready to test, run the runner.

run = runner.run();

Asserting

In our tests we can assert against pieces of the run

expect(run.getToken).to.deep.equal(select(getToken));
expect(run.fetchFoos).to.deep.equal(call(fetchFoos, action.bars, token));

Overwriting variables

Just pass in overrides for a given action when you call run.

run = runner.run({
  getToken: 'invalid-token',
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment