Last active
January 14, 2019 11:20
-
-
Save danrspencer/0450710f687b14e396b9a010e2a4e5a9 to your computer and use it in GitHub Desktop.
Redux Test Store
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 createTestStore = ( | |
reducer, | |
initialState = {}, | |
path = [], | |
thunkArguments = {} | |
) => { | |
const stateHistory = []; | |
const dispatchHistory = []; | |
const logHistory = store => next => action => { | |
dispatchHistory.push(action); | |
if (action.type) { | |
stateHistory.push(store.getState()); | |
} | |
return next(action); | |
}; | |
const middleware = applyMiddleware( | |
logHistory, | |
thunk.withExtraArgument(thunkArguments) | |
); | |
const reducers = path.reduceRight( | |
(acc, item) => combineReducers({ [item]: acc }), | |
reducer | |
); | |
const initial = path.reduceRight( | |
(acc, item) => ({ [item]: acc }), | |
initialState | |
); | |
const store = createReduxStore(reducers, initial, middleware); | |
const getPath = state => path.reduce((acc, item) => acc[item], state); | |
return { | |
...store, | |
dispatch: jest.fn(store.dispatch), | |
subscribe: jest.fn(store.subscribe), | |
getLocalState: () => getPath(store.getState()), | |
getStateHistory: () => [...stateHistory, store.getState()].map(getPath), | |
getDispatchHistory: () => [...dispatchHistory] | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment