-
-
Save aCandidMind/5192e23317501e62c51ecc7dd0744ead to your computer and use it in GitHub Desktop.
beating impurity in redux applications using dependency injection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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