diff --git a/src/components/ui/bsod/BsodMiddleware.js b/src/components/ui/bsod/BsodMiddleware.js new file mode 100644 index 0000000..84c827c --- /dev/null +++ b/src/components/ui/bsod/BsodMiddleware.js @@ -0,0 +1,16 @@ +export default function BsodMiddleware(dispatchBsod, logger) { + return { + catch(resp) { + if (resp + && resp.originalResponse + && /404|5\d\d/.test(resp.originalResponse.status) + ) { + dispatchBsod(); + + logger.warn('Unexpected response', {resp}); + } + + return Promise.reject(resp); + } + }; +} diff --git a/src/components/ui/bsod/factory.js b/src/components/ui/bsod/factory.js index d52bf6e..66b7932 100644 --- a/src/components/ui/bsod/factory.js +++ b/src/components/ui/bsod/factory.js @@ -2,23 +2,11 @@ import request from 'services/request'; import logger from 'services/logger'; import dispatchBsod, { inject } from './dispatchBsod'; +import BsodMiddleware from './BsodMiddleware'; export default function factory(store, stopLoading) { inject(store, stopLoading); // do bsod for 500/404 errors - request.addMiddleware({ - catch(resp) { - if (resp - && resp.originalResponse - && [5, 404].indexOf(resp.originalResponse.status) === 0 - ) { - dispatchBsod(); - - logger.warn('Unexpected response', {resp}); - } - - return Promise.reject(resp); - } - }); + request.addMiddleware(new BsodMiddleware(dispatchBsod, logger)); } diff --git a/tests/components/ui/bsod/BsodMiddleware.test.js b/tests/components/ui/bsod/BsodMiddleware.test.js new file mode 100644 index 0000000..50bb800 --- /dev/null +++ b/tests/components/ui/bsod/BsodMiddleware.test.js @@ -0,0 +1,45 @@ +import expect from 'unexpected'; +import sinon from 'sinon'; + +import BsodMiddleware from 'components/ui/bsod/BsodMiddleware'; + +describe('BsodMiddleware', () => { + [404, 500, 503, 555].forEach((code) => + it(`should dispatch for ${code}`, () => { + const resp = { + originalResponse: {status: code} + }; + + const dispatch = sinon.spy(); + const logger = {warn: sinon.spy()}; + + const middleware = new BsodMiddleware(dispatch, logger); + + return expect(middleware.catch(resp), 'to be rejected with', resp) + .then(() => { + expect(dispatch, 'was called'); + expect(logger.warn, 'to have a call satisfying', [ + 'Unexpected response', + {resp} + ]); + }); + }) + ); + + it('should not dispatch for 200', () => { + const resp = { + originalResponse: {status: 200} + }; + + const dispatch = sinon.spy(); + const logger = {warn: sinon.spy()}; + + const middleware = new BsodMiddleware(dispatch, logger); + + return expect(middleware.catch(resp), 'to be rejected with', resp) + .then(() => { + expect(dispatch, 'was not called'); + expect(logger.warn, 'was not called'); + }); + }); +});