Last active
January 13, 2017 11:03
-
-
Save carlesba/62f4cfd6938b179bdc0999e09df8d90c to your computer and use it in GitHub Desktop.
Util for testing thunks from redux-thunk using expect
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' // using expect by @mjackson | |
export default (state) => { | |
const spy = expect.createSpy() | |
const getState = () => state | |
const dispatch = (action) => typeof action === 'function' | |
? action(dispatch, getState) | |
: spy(action) | |
return {spy, getState, dispatch} | |
} |
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 {addUser} from './actions' | |
/* | |
Thunk to be tested | |
*/ | |
export const submitForm = (info) => (dispatch, getState) => { | |
const user = getUser(getState()) | |
if (user) { | |
fetch(FETCH_BODY) | |
.then((userId) => dispatch(addUser(userId))) | |
} else { | |
dispatch(errorMessage('no user defined')) | |
} | |
} |
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 mockThunk from './mock-thunk' | |
import {submitForm} from './thunks.js' | |
import mockState from 'path' | |
/* | |
As thunks can read the store, we need to mock it up as well | |
*/ | |
describe('submitForm', () => { | |
it('dispatches addUser when user is defined', () => { | |
const state = mockState() | |
const INFO = 'FORM_INFO' | |
const {spy, dispatch} = mockThunk(state) | |
dispatch(submitForm(INFO)) | |
expect(spy).toHaveBeenCalledWith(addUser(INFO)) | |
}) | |
it('dispatches error message when user is not defined', () => { | |
const state = mockState() | |
const INFO = 'FORM_INFO' | |
const {spy, dispatch} = mockThunk(state) | |
dispatch(submitForm(INFO)) | |
expect(spy).toHaveBeencalledWith(errorMessage('no user defined')) | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment