Sub topic 12
Testing a reducer
What this chapter assumes
You should know how to write a reducer, dispatch actions, and update state immutably, all covered in earlier chapters. You should also know basic test syntax (describe, it, expect). The examples use Vitest, and the same code works in Jest if you replace the import line.
Why reducers are easy to test
A reducer is a pure function: (state, action) => nextState. It reads only its two arguments, changes nothing outside itself, and returns the same output for the same input. A test needs no component, no DOM, no mocked timers, and no act() wrapper. Call the function and check what it returns.
This is a practical reason to prefer useReducer for state with many transitions. With useState, the update logic sits inside event handlers, so testing it means rendering the component and simulating clicks. With a reducer, each transition is a function call.
Put the reducer in its own module
To import a reducer into a test, you must export it. If you define it inside a component file, you would have to import the component module just to test the function. A separate module keeps the test free of JSX and React.
// 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 then imports it with import { todosReducer } from './todosReducer';. Nothing else about the component changes.
The shape of a reducer test
Each test follows three steps:
- Build a starting state.
- Build an action.
- Call the reducer and assert on the result.
import { describe, it, expect } from 'vitest';
import { todosReducer } from './todosReducer';
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 = [
{ id: 1, text: 'A', done: false },
{ id: 2, text: 'B', done: false },
];
const after = todosReducer(before, { type: 'toggled', id: 2 });
expect(after[0].done).toBe(false);
expect(after[1].done).toBe(true);
});
it('deletes a todo by id', () => {
const before = [
{ id: 1, text: 'A', done: false },
{ id: 2, text: 'B', done: true },
];
expect(todosReducer(before, { type: 'deleted', id: 1 })).toEqual([
{ id: 2, text: 'B', done: true },
]);
});
it('throws on unknown actions', () => {
expect(() => todosReducer([], { type: 'nope' })).toThrow('Unknown action: nope');
});
});Use toEqual to compare structure. toEqual ignores references, so it checks the values but not whether the reducer made a new object.
Test that the reducer does not mutate
The most common reducer bug is mutating the state you were given, for example todos.push(...) or todo.done = !todo.done. A mutating reducer often still returns the right-looking value, so a plain toEqual check passes. The bug then shows up in the app as a missing re-render, because React sees the same reference and skips the update.
There are two ways to catch it in a test.
Compare the input before and after
Take a snapshot of the input as plain data. Call the reducer. Check that the input still equals the snapshot.
it('does not mutate the previous state', () => {
const before = [{ id: 1, text: 'A', done: false }];
const snapshot = structuredClone(before);
todosReducer(before, { type: 'toggled', id: 1 });
expect(before).toEqual(snapshot);
});Freeze the input
Object.freeze makes an object read-only. In strict mode, which ES modules always use, writing to a frozen object throws a TypeError. A mutating reducer then fails loudly at the line that mutates. Object.freeze is shallow, so write a small helper that freezes nested objects too.
function deepFreeze(value) {
if (value && typeof value === 'object' && !Object.isFrozen(value)) {
Object.freeze(value);
Object.values(value).forEach(deepFreeze);
}
return value;
}
it('toggles without writing to frozen state', () => {
const before = deepFreeze([{ id: 1, text: 'A', done: false }]);
const after = todosReducer(before, { type: 'toggled', id: 1 });
expect(after[0].done).toBe(true);
expect(after).not.toBe(before);
});The freeze approach pins down the exact line of the bug. The snapshot approach also catches mutation of objects you forgot to freeze. Many teams use deepFreeze in a shared test helper and apply it to every initial state.
Test reference identity where it matters
Immutable updates should replace only the parts that change. React and React.memo rely on that: an unchanged item keeps its reference, so memoized children skip re-rendering. You can assert it with toBe, which compares references.
it('keeps untouched items by reference', () => {
const a = { id: 1, text: 'A', done: false };
const b = { id: 2, text: 'B', done: false };
const after = todosReducer([a, b], { type: 'toggled', id: 2 });
expect(after[0]).toBe(a);
expect(after[1]).not.toBe(b);
});This test fails if someone "simplifies" the reducer to rebuild every item, for example with todos.map(t => ({ ...t, done: t.id === action.id ? !t.done : t.done })).
Test the no-op case
React skips re-rendering when the reducer returns the same state value it was given, compared with Object.is. A reducer can use this on purpose by returning state for an action that changes nothing. Check that behavior with toBe.
// counterReducer.js
export function counterReducer(state, action) {
switch (action.type) {
case 'set':
if (state.count === action.value) return state;
return { count: action.value };
case 'incremented':
return { count: state.count + 1 };
default:
throw Error('Unknown action: ' + action.type);
}
}import { it, expect } from 'vitest';
import { counterReducer } from './counterReducer';
it('returns the same state object when the value is unchanged', () => {
const state = { count: 5 };
expect(counterReducer(state, { type: 'set', value: 5 })).toBe(state);
});
it('returns a new object when the value changes', () => {
const state = { count: 5 };
const next = counterReducer(state, { type: 'set', value: 6 });
expect(next).not.toBe(state);
expect(next).toEqual({ count: 6 });
});Only assert toBe(state) for reducers that intentionally promise a no-op. Do not add that promise to every reducer, because it constrains later refactors for no benefit.
Test sequences of actions
Real bugs often come from the order of actions: add, toggle, then delete. Since the reducer is a function, you can replay a list of actions with Array.prototype.reduce. The reducer already has the signature reduce expects.
it('handles a realistic sequence', () => {
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 }]);
});This is the closest a reducer test comes to an integration test. It also works well for state machines such as the loading, success, and error reducer from the async chapter. For that reducer, assert that a fetch_started action after an error clears the old error.
Test purity with repeated calls
In Strict Mode during development, React calls your reducer twice with the same arguments and discards one result. A reducer that depends on hidden state, such as Date.now(), Math.random(), or a module-level counter, gives different results on the two calls and produces visible bugs.
You can check this directly:
it('returns equal results for equal inputs', () => {
const state = [{ id: 1, text: 'A', done: false }];
const action = { type: 'toggled', id: 1 };
expect(todosReducer(state, action)).toEqual(todosReducer(state, action));
});Impure values should come in through the action. The todo component does this correctly by generating id in the event handler and passing it as action.id. A test can then supply a fixed id and get a deterministic result.
What to test and what to skip
| Test this | Skip this |
|---|---|
| Each action type produces the right next state | That React calls the reducer (that is React's job) |
| The input state is not mutated | Exact wording of the thrown message, unless callers depend on it |
| Unknown actions throw | Styling and markup of the component |
| Unchanged items keep their reference | Every possible combination of state shapes |
| Sequences of actions end in the expected state | Implementation details such as which array method you used |
Component tests still have a place. Write a small number of them to confirm that buttons dispatch the right actions and that the UI shows the state. Leave the detailed transition logic to the reducer tests, which run faster and fail with clearer messages.
Common errors
- Testing through the component only. The test fails when someone changes a label, even though the logic is fine. Test the reducer directly and keep component tests few.
- Asserting with
toBeon new objects.expect(after).toBe([...])always fails, because two arrays are never the same reference. UsetoEqualfor values andtoBeonly for identity checks. - Forgetting the default case. If a reducer silently returns
undefinedfor an unknown action, state becomesundefinedand the app crashes later. Test that it throws. - Sharing mutable state between tests. If one test builds
beforeat module level and a buggy reducer mutates it, later tests inherit the damage. Build the starting state inside each test, or freeze it. - Using random or time-based values inside the reducer. These break repeatability. Pass them in the action.
Exercise
A reducer handles { type: 'deleted', id } with todos.splice(todos.findIndex(t => t.id === action.id), 1); return todos;. A test calls it with [{ id: 1 }] and asserts expect(result).toEqual([]), and the test passes. Why is the reducer still wrong, and what two additions to the test would expose the problem?
Show answer
splice mutates the array that was passed in, and the reducer returns that same array. The result looks right, but React sees the same reference and may skip the re-render, and the previous state is corrupted. To expose it, pass a frozen input (for example with deepFreeze), which makes splice throw. Also assert that the original array is unchanged and that result is not the same reference as the input (expect(result).not.toBe(before)). The fix is return todos.filter(t => t.id !== action.id);.