Created
September 14, 2016 15:18
-
-
Save dmueller39/8764afc2c2c26ca2f164d416aabcafc9 to your computer and use it in GitHub Desktop.
Testing Async redux actions in jest
This file contains 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
function update(value) { | |
return (dispatch) => new Promise((resolve) => setImmediate( | |
() => { | |
dispatch({ type: 'UPDATE', value }); | |
resolve(); | |
} | |
)); | |
} | |
describe('async action', () => { | |
pit('dispatches an update action passing the action to resolve', | |
// returning a new Promise guarantees that | |
// pit will wait until the 'then' block has been called | |
() => new Promise((resolve) => { | |
// pass in resolve as our dispatch | |
update(1)(resolve); | |
}).then( | |
// by calling resolve as the dispatch we now can test the action | |
(action) => { | |
expect(action).not.toBeNull(); | |
expect(action.type).toBe('UPDATE'); | |
expect(action.value).toBe(1); | |
} | |
) | |
); | |
pit('dispatches an update action storing the results in a scoped variable', () => { | |
// collect the results in a variable with a shared scope between | |
// the 'promise' block and the 'then' block | |
let receivedAction = null; | |
// returning a new Promise guarantees that | |
// pit will wait until the 'then' block has been called | |
return new Promise((resolve) => { | |
const dispatch = (action) => { | |
receivedAction = action; | |
resolve(); | |
}; | |
update(1)(dispatch); | |
}).then( | |
// this block is only called if dispatch calls 'resolve' above | |
() => { | |
expect(receivedAction).not.toBeNull(); | |
expect(receivedAction.type).toBe('UPDATE'); | |
expect(receivedAction.value).toBe(1); | |
} | |
); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, Daniel,
I've been reading about async testing in jest and found one thing. It's possible to use parameter to the pit function and it will make a test wait until this parameter is called explicitly. For example,
IMHO, version with promises is less readable. What do you think?