From 877c11eb0086c41bec296e93c48fd043d72845cb Mon Sep 17 00:00:00 2001 From: taylorhakes Date: Tue, 30 Jun 2015 21:26:59 -0400 Subject: [PATCH] Throw error on undefined value from reducer function --- src/utils/composeReducers.js | 10 +++++++--- test/composeReducers.spec.js | 23 +++++++++++++++++++++++ 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/src/utils/composeReducers.js b/src/utils/composeReducers.js index e93887fabf..0292077fad 100644 --- a/src/utils/composeReducers.js +++ b/src/utils/composeReducers.js @@ -5,8 +5,12 @@ export default function composeReducers(reducers) { const finalReducers = pick(reducers, (val) => typeof val === 'function'); return function Composition(atom = {}, action) { - return mapValues(finalReducers, (store, key) => - store(atom[key], action) - ); + return mapValues(finalReducers, (reducer, key) => { + const state = reducer(atom[key], action); + if (typeof state === 'undefined') { + throw new Error(`Reducer ${key} returns undefined. By default reducer should return original state.`); + } + return state; + }); }; } diff --git a/test/composeReducers.spec.js b/test/composeReducers.spec.js index c0ce3c919e..37af766a42 100644 --- a/test/composeReducers.spec.js +++ b/test/composeReducers.spec.js @@ -29,5 +29,28 @@ describe('Utils', () => { Object.keys(reducer({}, { type: 'push' })) ).toEqual(['stack']); }); + it('should throw an error if undefined return from reducer', () => { + const reducer = composeReducers({ + stack: (state = []) => state, + bad: (state = [], action) => { + if (action.type === 'something') { + return state; + } + } + }); + expect(() => reducer({}, {type: '@@testType'})).toThrow(); + }); + it('should throw an error if undefined return not by default', () => { + const reducer = composeReducers({ + stack: (state = []) => state, + bad: (state = 1, action) => { + if (action.type !== 'something') { + return state; + } + } + }); + expect(reducer({}, {type: '@@testType'})).toEqual({stack: [], bad: 1}); + expect(() => reducer({}, {type: 'something'})).toThrow(); + }); }); });