Skip to content

Commit 673f84c

Browse files
author
taylorhakes
committed
Throw error on undefined value from reducer function
1 parent 34d90b9 commit 673f84c

File tree

2 files changed

+30
-3
lines changed

2 files changed

+30
-3
lines changed

src/utils/composeReducers.js

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,12 @@ export default function composeReducers(reducers) {
55
const finalReducers = pick(reducers, (val) => typeof val === 'function');
66

77
return function Composition(atom = {}, action) {
8-
return mapValues(finalReducers, (store, key) =>
9-
store(atom[key], action)
10-
);
8+
return mapValues(finalReducers, (reducer, key) => {
9+
const state = reducer(atom[key], action);
10+
if (typeof state === 'undefined') {
11+
throw new Error(`Reducer ${key} returns undefined. By default reducer should return original state.`);
12+
}
13+
return state;
14+
});
1115
};
1216
}

test/composeReducers.spec.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,5 +29,28 @@ describe('Utils', () => {
2929
Object.keys(reducer({}, { type: 'push' }))
3030
).toEqual(['stack']);
3131
});
32+
it('should throw an error if undefined return from reducer', () => {
33+
const reducer = composeReducers({
34+
stack: (state = []) => state,
35+
bad: (state = [], action) => {
36+
if (action.type === 'something') {
37+
return state;
38+
}
39+
}
40+
});
41+
expect(() => reducer({}, {type: '@@testType'})).toThrow();
42+
});
43+
it('should throw an error if undefined return not by default', () => {
44+
const reducer = composeReducers({
45+
stack: (state = []) => state,
46+
bad: (state = 1, action) => {
47+
if (action.type !== 'something') {
48+
return state;
49+
}
50+
}
51+
});
52+
expect(reducer({}, {type: '@@testType'})).toEqual({stack: [], bad: 1});
53+
expect(() => reducer({}, {type: 'something'})).toThrow();
54+
});
3255
});
3356
});

0 commit comments

Comments
 (0)