Redux: How to write tests regarding Action Creators which return functions?

Created on 10 Sep 2015  路  6Comments  路  Source: reduxjs/redux

It's mentioned in the documentation:

In Redux, action creators are functions which return plain objects. When testing action creators we want to test whether the correct action creator was called and also whether the right action was returned.

However, action creators can also return functions like this:

(dispatch, getState) => {...}

In this case, how do I write tests? It's not a simple checking object equality anymore.

Thank you

question

Most helpful comment

The counter example app has some tests that cover this.

 it('incrementIfOdd should create increment action', () => {
    const fn = actions.incrementIfOdd();
    expect(fn).toBeA('function');
    const dispatch = expect.createSpy();
    const getState = () => ({ counter: 1 });
    fn(dispatch, getState);
    expect(dispatch).toHaveBeenCalledWith({ type: actions.INCREMENT_COUNTER });
  });

Maybe an idea to add this to the documentation?

All 6 comments

The counter example app has some tests that cover this.

 it('incrementIfOdd should create increment action', () => {
    const fn = actions.incrementIfOdd();
    expect(fn).toBeA('function');
    const dispatch = expect.createSpy();
    const getState = () => ({ counter: 1 });
    fn(dispatch, getState);
    expect(dispatch).toHaveBeenCalledWith({ type: actions.INCREMENT_COUNTER });
  });

Maybe an idea to add this to the documentation?

@por
Thank you very much for the help!

Duplicate of https://github.com/rackt/redux/issues/546.
See https://github.com/rackt/redux/issues/546#issuecomment-134789273.

Maybe an idea to add this to the documentation?

I'd happily accept a pull request.

However, action creators can also return functions like this:

(dispatch, getState) => {...}

I see it's not true anymore... Did the API change? I guess I should use https://github.com/gaearon/redux-thunk instead.

Yes, use thunk if you want to have this.

Also, there is a related issue: https://github.com/gaearon/redux-thunk/issues/14

Was this page helpful?
0 / 5 - 0 ratings