Testing Reducers
We'll test Redux reducers in our Weather app that's built with React and Redux.
We'll cover the following...
The reducer is, again, a pure function! It’s quite easy to see what we need to validate actually, basically every case
of our switch
needs to have a test:
export default function mainReducer(state = initialState, action) {
switch (action.type) {
case 'CHANGE_LOCATION':
return state.set('location', action.location);
case 'SET_DATA':
return state.set('data', fromJS(action.data));
case 'SET_DATES':
return state.set('dates', fromJS(action.dates));
case 'SET_TEMPS':
return state.set('temps', fromJS(action.temps));
case 'SET_SELECTED_DATE':
return state.setIn(['selected', 'date'], action.date);
case 'SET_SELECTED_TEMP':
return state.setIn(['selected', 'temp'], action.temp);
default:
return state;
}
}
Let’s showcase this on the 'CHANGE_LOCATION'
case, first create a reducer.test.js
file in the __tests__ /
directory, import the reducer and add the basic structure:
// __tests__/reducer.test.js
import mainReducer from '../reducer';
describe('mainReducer', function() {
});
The first branch of the switch statement we’ll test is the default
one – if we don’t pass any state and an empty action in it should return the initial state. The thing is that the initialState
is an immutable object, so we’ll need to import fromJS
too:
// __tests__/reducer.test.js
import mainReducer from '../reducer';
import { fromJS } from 'immutable';
describe('mainReducer', function() {
it('should return the initial state', function() {
expect(mainReducer(undefined,
...