diff --git a/src/__tests__/handleActions-test.js b/src/__tests__/handleActions-test.js index 5ecaa349..6f75801d 100644 --- a/src/__tests__/handleActions-test.js +++ b/src/__tests__/handleActions-test.js @@ -236,4 +236,28 @@ describe('handleActions', () => { message: 'hello---me: goodbye' }); }); + + it('should return default state with empty handlers and undefined previous state', () => { + const { unhandled } = createActions('UNHANDLED'); + const reducer = handleActions({}, defaultState); + + expect(reducer(undefined, unhandled())).to.deep.equal(defaultState); + }); + + it('should return previous defined state with empty handlers', () => { + const { unhandled } = createActions('UNHANDLED'); + const reducer = handleActions({}, defaultState); + + expect(reducer({ counter: 10 }, unhandled())).to.deep.equal({ counter: 10 }); + }); + + it('should throw an error if handlers object has the wrong type', () => { + const wrongTypeHandlers = [1, 'string', [], null]; + + wrongTypeHandlers.forEach(wrongTypeHandler => { + expect( + () => handleActions(wrongTypeHandler, defaultState) + ).to.throw(Error, 'Expected handlers to be an plain object.'); + }); + }); }); diff --git a/src/handleActions.js b/src/handleActions.js index 69d7a83d..2d7fbf3f 100644 --- a/src/handleActions.js +++ b/src/handleActions.js @@ -1,8 +1,14 @@ +import isPlainObject from 'lodash/isPlainObject'; +import reduceReducers from 'reduce-reducers'; +import invariant from 'invariant'; import handleAction from './handleAction'; import ownKeys from './ownKeys'; -import reduceReducers from 'reduce-reducers'; export default function handleActions(handlers, defaultState) { + invariant( + isPlainObject(handlers), + 'Expected handlers to be an plain object.' + ); const reducers = ownKeys(handlers).map(type => handleAction( type, @@ -11,5 +17,5 @@ export default function handleActions(handlers, defaultState) { ) ); const reducer = reduceReducers(...reducers); - return (state, action) => reducer(state, action); + return (state = defaultState, action) => reducer(state, action); }