Skip to content

Instantly share code, notes, and snippets.

@c089
Last active April 24, 2016 10:25
Show Gist options
  • Save c089/ed08d81993f42d2f56bf to your computer and use it in GitHub Desktop.
Save c089/ed08d81993f42d2f56bf to your computer and use it in GitHub Desktop.
beating impurity in redux applications using dependency injection
/* First, since our reducers need to be free of side-effects, we move them to an
action creator. Note the double arrow function: The outer function is only there
dependency injection. It's a function that creates an action creator, but I
don't really want to call it an action creator creator ;) */
const impureActionCreator = (idGenerator) => () => ({type: 'FOO_ACTION', id: randomSource.randomId()});
// Our reducer will now stay free of side effects, and we already have `action.id` when it's called
const reducer = (state, action) => // ...
// we can unit test our action creator by injecting a pure stub
test('impure action creator', () => {
const idGeneratorStub = () => 42;
const previousState = // ...
const newState = reducer(previousState, impureActionCreator(idGeneratorStub));
expect(newState) // ...
});
// in the app entry point we inject the actually impure implementation
const app = createApp({
// ...
idGenerator: createCountingIdGeneratorStartingAt(1)
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment