lelandrichardson / redux-pack

Sensible promise handling and middleware for redux
MIT License
1.33k stars 60 forks source link

Examples of how to test reducer #32

Closed einarq closed 7 years ago

einarq commented 7 years ago

Could you perhaps provide an example of how you test the reducer for actions that are created with redux-pack? Do you have to create an instance of the actual store and dispatch it as you would in the app?

evandavis commented 7 years ago

I recommend writing duck tests. We use redux-mock-store instead of a real store for tests.

Your test should dispatch an action and then use selectors to assert the new state.

lelandrichardson commented 7 years ago

@einarq I agree with @evandavis, you should not need or want to create a store in order to test a reducer or action creators. In fact, I consider this is one of the primary benefits of redux's architecture.

Right now, testing reducers that respond to redux-pack actions does unfortunately require you know a little bit about the implementation of it. We have discussed exporting test utilities in order to make this easier. Right now, it would go something like this:

import { LIFECYCLE, KEY } from 'redux-pack';
import FooReducer from '../path/to/FooReducer';

// this utility method will make an action that redux pack understands
function makePackAction(lifecycle, { type, payload, meta={} }) {
  return {
    type,
    payload,
    meta: {
      ...meta,
      [KEY.LIFECYCLE]: lifecycle,
    },
  }
}

// your test code would then look something like...
const initialState = { ... };
const action = makePackAction(LIFECYCLE.START, { type: 'FOO', payload: { ... } });
const endState = FooReducer(initialState, action);
assertDeepEqual(endState, expectedEndState);