Last active
May 17, 2018 18:42
-
-
Save kolodny/50e7384188bb5dc41ebb to your computer and use it in GitHub Desktop.
testing redux thunk middleware
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
export const doTheThing = () => (dispatch, getState) => { | |
const users = getState(); | |
dispatch({ | |
type: 'THE_THING', | |
users, | |
}); | |
}; |
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
import expect from 'expect'; | |
describe('doTheThing', () => { | |
it('should return a function', () => { | |
expect(doTheThing()).toBeA('function'); | |
}) | |
it('dispatch a doTheThing action', () => { | |
const getState = () => ({users: 'foo'}); | |
const dispatch = expect.createSpy(); | |
doTheThing()(dispatch, getState); | |
expect(dispatch).toHaveBeenCalledWith({type: 'THE_THING', users: 'foo'}); | |
}) | |
}); |
You should keep in mind that this approach will only work if dispatch() is called synchronously. If it is called asynchronously, it will do the expect(dispatch)...
before dispatch has actually been called ;)
I wrote something similar, but promise-based to care for my asynchronous use case. The problem about my approach is that it will only work properly if you dispatch() once, since the promise will resolve after the first call...
PS: This might also be useful! reduxjs/redux#546
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It is worth noting that first test becomes redundant with the 2nd.