Skip to content

Instantly share code, notes, and snippets.

@danrspencer
Last active January 14, 2019 11:20
Show Gist options
  • Save danrspencer/0450710f687b14e396b9a010e2a4e5a9 to your computer and use it in GitHub Desktop.
Save danrspencer/0450710f687b14e396b9a010e2a4e5a9 to your computer and use it in GitHub Desktop.
Redux Test Store
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