Created
August 17, 2016 18:41
-
-
Save alicekao/36d7d87906ff9f2d64955fce8d53031a to your computer and use it in GitHub Desktop.
How to mock store to test actions in a redux app
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
// Our action to fetch all places in actions/index.js | |
export function fetchPlaces() { | |
return dispatch => { | |
return axios.get('/api/places/fetchAll') | |
.then(resp => { | |
dispatch(updatePlaces(resp.data)); | |
}) | |
.catch(err => { | |
console.log('Couldn\'t fetch places: ', err); | |
dispatch(authError(err)); | |
}); | |
} | |
} | |
// In actions/actions.spec.js | |
import configureStore from 'redux-mock-store'; | |
import promiseMiddleware from 'redux-thunk'; | |
import expect, { createSpy } from 'expect'; | |
import * as actions from './index'; | |
import * as types from './types'; | |
// Create our mock store with our promise middelware | |
const mockStore = configureStore([promiseMiddleware]); | |
describe('Async actions: ', () => { | |
it('Fetches places', () => { | |
const store = mockStore({}); // Ceate a mocked-store instance with an initial empty state | |
return store.dispatch(actions.fetchPlaces()) | |
.then(() => { | |
expect(store.getActions().length).toBe(1); // getActions() returns an array of the dispatched actions | |
expect(store.getActions()[0].payload.data).toEqual(expectedPlaces); | |
expect(store.getActions()[0].type).toBe(types.UPDATE_PLACES); | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment