Skip to content

Instantly share code, notes, and snippets.

@lxanders
Last active March 27, 2019 09:29
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lxanders/90ed310bac364e7e4537e3a5f96cb7f1 to your computer and use it in GitHub Desktop.
Save lxanders/90ed310bac364e7e4537e3a5f96cb7f1 to your computer and use it in GitHub Desktop.
// note: I'm using redux-actions in here, so the actions might look a bit different than you are used too
// note: This is not complete but the concepts are
// excerpt from app.js
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import fetch from 'isomorphic-fetch'
// note: you could totally leave out the fetch argument here if you set a default (as I do in my actions)
// I'm right now not absolutely sure how I will handle this in the future (the way it is now it is a bit redundant)
const store = createStore(
reducers,
applyMiddleware(thunk.withExtraArgument(fetch))
);
// excerpt from an async action (a thunk)
import fetch from 'isomorphic-fetch'
export function fetchSomething() {
// the withExtraArgument function injects a third argument here (you could use an object too and
// destructure it where you need the different parts if you need more things injected) - if we wouldn't
// have set it above in the root app, we would still fall back to fetch
return (dispatch, getState, fetchModule = fetch) => {
return fetchModule('http://localhost/api/something', { method: 'get' })
.then((response) => {
if (response.status === 200) {
return response.json();
}
throw new Error(`${response.status}: ${response.statusText}`);
})
.then((something) => dispatch(someActionThatInformsTheStoreToStoreIt(something)))
.catch((error) => dispatch(anErrorActionCreatorEgSetErrorThatJustStoresTheErrorMessage(error.message)));
};
}
// excerpt from a test file for that action above
import configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import myThunkActionFromAbove from './some/action';
it('should execute some actions', function () {
// this would do the trick and would now just work for simple cases - if you e.g. want a more realistic
// behavior test you can use nock in there
const fetchModule = sinon.stub().rejects(new Error('some error'));
const mockStore = configureStore([ thunk.withExtraArgument(fetchModule) ]);
const store = mockStore();
return store.dispatch(myThunkActionFromAbove())
.then(() => {
expect(store.getActions()).to.deep.equal({ type: 'SET_ERROR', payload: 'some error' });
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment