Skip to content

Commit

Permalink
Add test case & improve error message wording
Browse files Browse the repository at this point in the history
* Add a test case to verify reducer has a catch-all clause for unknown action types
* Improve error message wording
  • Loading branch information
msafi committed Nov 29, 2015
1 parent ae16bad commit 6b46189
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 8 deletions.
13 changes: 6 additions & 7 deletions src/utils/combineReducers.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,19 +59,18 @@ function assertReducerSanity(reducers) {
if (typeof initialState === 'undefined') {
throw new Error(
`Reducer "${key}" returned undefined during initialization. ` +
`If the state passed to the reducer is undefined, you must ` +
`explicitly return the initial state. The initial state may ` +
`not be undefined.`
`Reducers should never return undefined. Make sure this reducer ` +
`has a catch-all clause for unknown action types and that it returns a ` +
`default initial state if the state passed to it is undefined.`
)
}

var randomState = Math.random().toString(36).substring(7).split('').join('.')
if (reducer(randomState, { type: ActionTypes.INIT }) !== randomState) {
throw new Error(
`Reducer "${key}" did not return the current state when probed with a random type. ` +
`You must return the current state for any unknown actions, unless it is undefined, ` +
`in which case you must return the initial state, regardless of the ` +
`action type. The initial state may not be undefined.`
`Reducer "${key}" did not return the current state when probed with a ` +
`random action type. You must return the current state for any unknown ` +
`action types.`
)
}
})
Expand Down
21 changes: 20 additions & 1 deletion test/utils/combineReducers.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,25 @@ describe('Utils', () => {
)
})

it('throws an error if reducer does not have a catch-all clause for unknown action types', () => {
const reducer = combineReducers({
counter(state = 0, action) {
switch (action.type) {
case 'increment':
return state + 1
case 'decrement':
return state - 1
case undefined:
return state
}
}
})

expect(() => reducer()).toThrow(
/"counter".*initialization/
)
})

it('catches error thrown in reducer when initializing and re-throw', () => {
const reducer = combineReducers({
throwingReducer() {
Expand Down Expand Up @@ -151,7 +170,7 @@ describe('Utils', () => {
expect(reducer(initialState, { type: 'increment' })).toNotBe(initialState)
})

it('throws an error if reducer does not return current state for all unknown action types', () => {
it('throws an error if reducer does not return current state for unknown action types', () => {
const reducer = combineReducers({
counter(state, action) {
switch (action.type) {
Expand Down

0 comments on commit 6b46189

Please sign in to comment.