Skip to content

Instantly share code, notes, and snippets.

@carlesba
Last active January 13, 2017 11:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carlesba/62f4cfd6938b179bdc0999e09df8d90c to your computer and use it in GitHub Desktop.
Save carlesba/62f4cfd6938b179bdc0999e09df8d90c to your computer and use it in GitHub Desktop.
Util for testing thunks from redux-thunk using expect
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}
}
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'))
}
}
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