Skip to content

Instantly share code, notes, and snippets.

@OlegLustenko
Last active February 22, 2018 12:31
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 OlegLustenko/da3bcf420151b0230ac3fe30920fc768 to your computer and use it in GitHub Desktop.
Save OlegLustenko/da3bcf420151b0230ac3fe30920fc768 to your computer and use it in GitHub Desktop.
The Complete Redux book
import 'whatwg-fetch';
import {API} from 'consts';
import {apiStarted, apiFinished, apiError} from 'actions/ui';
const apiMiddleware = ({dispatch}) => (next) => (action) => {
if (action.type !== API) {
return next(action);
}
const {url, success} = action.payload;
dispatch(apiStarted());
return fetch(url)
.then((response) => response.json())
.then((response) => {
dispatch(apiFinished());
dispatch(success(response));
})
.catch(({status, statusText}) => dispatch(apiError(new Error({status, statusText}))));
};
export default apiMiddleware;
import apiMiddleware from 'middleware/api';
import {mockFetch, mockFetchError} from 'test-utils';
import {API_STARTED, API_FINISHED, API, API_ERROR} from 'consts';
const data = {title: 'hello'};
const setData = (data) => ({
type: 'SET_DATA',
payload: data,
});
const apiAction = () => ({
type: API,
payload: {
success: setData,
url: 'fake.json',
},
});
describe('api middleware', () => {
let next, dispatch, middleware;
beforeEach(() => {
next = jest.fn();
dispatch = jest.fn();
middleware = apiMiddleware({dispatch})(next);
});
describe('general', () => {
// TODO
});
describe('success', () => {
// TODO
});
describe('error', () => {
// TODO
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment