Skip to content

Commit feb9386

Browse files
webholicsyangmillstheory
authored andcommitted
Use defaultState in handleActions with empty reducer map (#203)
close #202
1 parent bac4527 commit feb9386

File tree

2 files changed

+32
-2
lines changed

2 files changed

+32
-2
lines changed

src/__tests__/handleActions-test.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,4 +236,28 @@ describe('handleActions', () => {
236236
message: 'hello---me: goodbye'
237237
});
238238
});
239+
240+
it('should return default state with empty handlers and undefined previous state', () => {
241+
const { unhandled } = createActions('UNHANDLED');
242+
const reducer = handleActions({}, defaultState);
243+
244+
expect(reducer(undefined, unhandled())).to.deep.equal(defaultState);
245+
});
246+
247+
it('should return previous defined state with empty handlers', () => {
248+
const { unhandled } = createActions('UNHANDLED');
249+
const reducer = handleActions({}, defaultState);
250+
251+
expect(reducer({ counter: 10 }, unhandled())).to.deep.equal({ counter: 10 });
252+
});
253+
254+
it('should throw an error if handlers object has the wrong type', () => {
255+
const wrongTypeHandlers = [1, 'string', [], null];
256+
257+
wrongTypeHandlers.forEach(wrongTypeHandler => {
258+
expect(
259+
() => handleActions(wrongTypeHandler, defaultState)
260+
).to.throw(Error, 'Expected handlers to be an plain object.');
261+
});
262+
});
239263
});

src/handleActions.js

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,14 @@
1+
import isPlainObject from 'lodash/isPlainObject';
2+
import reduceReducers from 'reduce-reducers';
3+
import invariant from 'invariant';
14
import handleAction from './handleAction';
25
import ownKeys from './ownKeys';
3-
import reduceReducers from 'reduce-reducers';
46

57
export default function handleActions(handlers, defaultState) {
8+
invariant(
9+
isPlainObject(handlers),
10+
'Expected handlers to be an plain object.'
11+
);
612
const reducers = ownKeys(handlers).map(type =>
713
handleAction(
814
type,
@@ -11,5 +17,5 @@ export default function handleActions(handlers, defaultState) {
1117
)
1218
);
1319
const reducer = reduceReducers(...reducers);
14-
return (state, action) => reducer(state, action);
20+
return (state = defaultState, action) => reducer(state, action);
1521
}

0 commit comments

Comments
 (0)