Unknown Actions
Learn how to resolve issues when there are unknown actions present.
One last issue to test with reducers is that they gracefully handle unknown actions and return the original state passed to them without modifications.
Since every action can propagate to the whole reducer tree, the reducer needs to return the original state and not a modified copy. This will allow UI libraries to identify changes in the tree using reference comparison.
We can do this as follows:
it('should handle unknown actions', () => {
expect(reducer(initialState, { type: 'FAKE' })).toBe(initialState);
});
An important thing to note about this test is the use of .toBe()
instead of .toEqual()
or .toMatchSnapshot()
. Unlike the other methods, .toBe()
expects the result of the reducer to be the exact object, not a similar object with the same data:
const a = { name: 'Kipi' };
const b = { name: 'Kipi' };
it('passing test', () => expect(a).toEqual(b));
it('failing test', () => expect(a).toBe(b));
The main goal of this test is to verify that our reducer returns the original state if the action sent was not intended for it:
const reducer = (state = initialState, action) => {
switch (action.type) {
case ADD_RECIPE: return state.concat({ title: action.payload })
}
return state;
};
Get hands-on with 1400+ tech skills courses.