Sub topic 12
Testing a reducer
This chapter assumes you can write a reducer with a switch on action.type, that you know why reducers must be pure and update state immutably, and that you have a JavaScript test runner such as Vitest set up. The examples use Vitest. Jest uses the same describe, it, and expect calls.
Why reducers are easy to test
A reducer is a plain function: (state, action) => nextState. It doesn't use hooks, the DOM, or timers, and it doesn't read anything outside its arguments. To test it, you call it with a state and an action, then check the value it returns. You don't need to render a component, click buttons, or mock React.
This is one of the main reasons to move logic into a reducer. A component test has to go through the UI. A reducer test only checks the rules for changing state.
Export the reducer
Your reducer must be exported separately from the component so a test can import it. Put it in its own file:
// todosReducer.js
export function todosReducer(todos, action) {
switch (action.type) {
case 'added':
return [...todos, { id: action.id, text: action.text, done: false }];
case 'toggled':
return todos.map(t =>
t.id === action.id ? { ...t, done: !t.done } : t
);
case 'deleted':
return todos.filter(t => t.id !== action.id);
default:
throw Error('Unknown action: ' + action.type);
}
}The component file then imports todosReducer and passes it to useReducer.
Write one test per action
Each test follows the same three steps: build a starting state, call the reducer with an action, and assert on the result.
// todosReducer.test.js
import { describe, it, expect } from 'vitest';
import { todosReducer } from './todosReducer';
const todo = (id, done = false) => Object.freeze({ id, text: 'Task ' + id, done });
describe('todosReducer', () => {
it('adds a todo', () => {
const after = todosReducer([], { type: 'added', id: 1, text: 'Write tests' });
expect(after).toEqual([{ id: 1, text: 'Write tests', done: false }]);
});
it('toggles only the matching todo', () => {
const before = Object.freeze([todo(1), todo(2)]);
const after = todosReducer(before, { type: 'toggled', id: 2 });
expect(after[0].done).toBe(false);
expect(after[1].done).toBe(true);
});
it('deletes the matching todo', () => {
const before = Object.freeze([todo(1), todo(2)]);
const after = todosReducer(before, { type: 'deleted', id: 1 });
expect(after).toEqual([todo(2)]);
});
it('throws on unknown actions', () => {
expect(() => todosReducer([], { type: 'nope' })).toThrow('Unknown action: nope');
});
});Run the tests with npx vitest run.
Catch mutation with frozen state
A reducer that mutates its input can still pass a test that only checks the return value. The test above uses Object.freeze to catch this. If the reducer calls todos.push(...) or assigns todo.done = true on a frozen value, JavaScript throws an error in strict mode (ES modules are strict by default), and the test fails.
Object.freeze is shallow. It protects the array and each todo object only because the helper freezes both. For deeper state, freeze each level or use a small deep-freeze helper.
Test sequences of actions
Real usage is a series of actions. Because a reducer is a function of state and action, Array.prototype.reduce can replay the series:
import { it, expect } from 'vitest';
import { todosReducer } from './todosReducer';
it('handles add, toggle, then delete', () => {
const actions = [
{ type: 'added', id: 1, text: 'A' },
{ type: 'added', id: 2, text: 'B' },
{ type: 'toggled', id: 1 },
{ type: 'deleted', id: 2 },
];
const result = actions.reduce(todosReducer, []);
expect(result).toEqual([{ id: 1, text: 'A', done: true }]);
});reduce passes (accumulator, item) to the callback, and a reducer takes (state, action), so the two line up. This is the same idea the name "reducer" comes from.
Common mistakes
- Not exporting the reducer. If it only exists inside the component file, you are forced to test through the UI.
- Asserting only on the new state. Also check that the old state is unchanged, or freeze it.
- Forgetting the default case. An unknown action should fail loudly, and a test should prove it does.
- Using
Date.now()orMath.random()inside the reducer. This makes it impure and its tests unreliable. Generate ids in the event handler and pass them in the action, asnextId++does in the todo example.
Exercise
A reducer handles a 'cleared' action by running todos.length = 0 and returning todos. A test calls it with a normal array and checks expect(after).toEqual([]). The test passes. What is wrong, and how would you change the test to expose the problem?
Show answer
The reducer mutates its input and returns the same array reference. React would see the same state object and could skip the re-render, and the old state is changed. The toEqual([]) check can't see this. Pass a frozen array, such as Object.freeze([todo(1)]), so the mutation throws and the test fails. You could also assert expect(after).not.toBe(before). Fix the reducer to return a new array: return [].