Skip to content
Diego Haz edited this page May 19, 2017 · 6 revisions

Reducers are pure functions which are called sequentially when some action is dispatched. With them you can perform state changes based on the dispatched action.

A simple reducer will look like this:

const reducer = (state, action) => {
  switch (action.type) {
    case 'RESOURCE_CREATE':
      return {
        ...state,
        list: [action.data, ...state.list],
      }
    default:
      return state
  }
}

Unit testing reducers

As well as actions, reducers are pure functions and therefore very easy to unit test:

test('RESOURCE_CREATE', () => {
  const state = {}
  const action = {
    type: 'RESOURCE_CREATE', 
    data: { title: 'Hi!' },
  }
  const expectedState = {
    list: [{ title: 'Hi!' }],
  }
  expect(reducer(state, action)).toEqual(expectedState)
})
Clone this wiki locally