Skip to content

Testing Reducers

The Course
•
20 min study

A reducer doesn't need React, a browser or a screen. It takes two values and returns a third. That makes it the easiest part of an app to test: call it, and check what comes back.

Tests in the lab

On your own computer you'd use Vitest, as in React Beginner Day 7. So you can practice here, the lab has a tiny test runner in testing.js with the same shape: test(name, fn), and expectEqual(actual, expected), which throws if the two differ. The page lists each test with ✓ or ✗.

Reducer tests React · 6 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { results } from "./testing.js"; import "./boardReducer.test.js"; export default function App() { const failed = results.filter((r) => !r.passed).length; return ( <main> <h1>{failed === 0 ? `All ${results.length} tests pass` : `${failed} of ${results.length} tests fail`}</h1> <ul className="cards"> {results.map((r) => ( <li key={r.name} className="card"> {r.passed ? "✓" : "✗"} {r.name} {!r.passed && <div className="error">{r.message}</div>} </li> ))} </ul> </main> ); } // Every change to the cards, in one place. A reducer takes the current state // and an action describing what happened, and returns the next state. export function boardReducer(cards, action) { switch (action.type) { case "card_added": return [...cards, { id: action.id, title: action.title, column: "todo", minutes: action.minutes }]; case "card_moved": return cards.map((card) => (card.id === action.id ? { ...card, column: action.column } : card)); case "card_removed": return cards.filter((card) => card.id !== action.id); default: throw new Error(`Unknown action: ${action.type}`); } } import { test, expectEqual } from "./testing.js"; import { boardReducer } from "./boardReducer.js"; const cards = [ { id: 1, title: "Read", column: "todo", minutes: 20 }, { id: 2, title: "Build", column: "doing", minutes: 30 }, ]; test("card_added adds a card to To do", () => { const next = boardReducer(cards, { type: "card_added", id: 3, title: "Test", minutes: 15 }); expectEqual(next.length, 3); expectEqual(next[2], { id: 3, title: "Test", column: "todo", minutes: 15 }); }); test("card_added leaves the old array alone", () => { boardReducer(cards, { type: "card_added", id: 3, title: "Test", minutes: 15 }); expectEqual(cards.length, 2); }); test("card_moved changes only that card's column", () => { const next = boardReducer(cards, { type: "card_moved", id: 1, column: "done" }); expectEqual(next.map((card) => card.column), ["done", "doing"]); }); // A tiny test runner, so tests can run in the lab. On your own computer you'd // use Vitest, which works the same way: named tests and expectations. export const results = []; export function test(name, fn) { try { fn(); results.push({ name, passed: true }); } catch (error) { results.push({ name, passed: false, message: error.message }); } } export function expectEqual(actual, expected) { const a = JSON.stringify(actual); const e = JSON.stringify(expected); if (a !== e) throw new Error(`Expected ${e}, got ${a}`); } body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.

Read the three tests. Each one builds a starting state, dispatches one action by calling the reducer directly, and checks the result:

JavaScript
test("card_moved changes only that card's column", () => {
  const next = boardReducer(cards, { type: "card_moved", id: 1, column: "done" });
  expectEqual(next.map((card) => card.column), ["done", "doing"]);
});

The second test checks something easy to forget: that the old array is unchanged after card_added.

Make a test fail on purpose

A test you've never seen fail might not be testing anything. Break the reducer: change card_moved to return cards unchanged. Press Run. The page says 1 of 3 tests fail, names the test, and shows Expected ["done","doing"], got ["todo","doing"]. Put the reducer back.

Would these tests catch the last lesson's bug?

In Writing Reducers, card_moved changed the card in place and returned the same array. Put that bug into this lab's boardReducer.js:

JavaScript
case "card_moved": {
  const card = cards.find((c) => c.id === action.id);
  card.column = action.column;
  return cards;
}

Predict what the page says, then press Run.

Check your prediction

All 3 tests pass. The move test only looks at the columns of the result, and the result really does say ["done", "doing"]: the bug changed the old card to get there. The "leaves the old array alone" test only checks card_added. Nothing checks that card_moved leaves the old state alone.

Add the missing test:

JavaScript
test("card_moved leaves the old cards alone", () => {
  const next = boardReducer(cards, { type: "card_moved", id: 1, column: "done" });
  expectEqual(cards[0].column, "todo");
  expectEqual(next === cards, false);
});

With the buggy reducer, the page now says 1 of 4 tests fail. Put the map version back and all four pass. A suite only guards against the mistakes someone wrote a test for, so test what each action must leave alone, not only what it changes.

What to test

For each action, test:

  • The ordinary case: the change it should make.
  • What it must leave alone: other cards, other fields, the old state.
  • The edge cases: an id that doesn't exist, the last column, an empty list.
  • Unknown actions throw.

You don't need to test React itself. If the reducer is right and the component dispatches the right actions, the screen follows.

Your turn

Exercise

Test card_removed

Add two tests for card_removed: one that removes the right card, and one showing that an id that doesn't exist leaves the cards as they were.

Your working space React · 6 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { results } from "./testing.js"; import "./boardReducer.test.js"; export default function App() { const failed = results.filter((r) => !r.passed).length; return ( <main> <h1>{failed === 0 ? `All ${results.length} tests pass` : `${failed} of ${results.length} tests fail`}</h1> <ul className="cards"> {results.map((r) => ( <li key={r.name} className="card"> {r.passed ? "✓" : "✗"} {r.name} {!r.passed && <div className="error">{r.message}</div>} </li> ))} </ul> </main> ); } // Every change to the cards, in one place. A reducer takes the current state // and an action describing what happened, and returns the next state. export function boardReducer(cards, action) { switch (action.type) { case "card_added": return [...cards, { id: action.id, title: action.title, column: "todo", minutes: action.minutes }]; case "card_moved": return cards.map((card) => (card.id === action.id ? { ...card, column: action.column } : card)); case "card_removed": return cards.filter((card) => card.id !== action.id); default: throw new Error(`Unknown action: ${action.type}`); } } import { test, expectEqual } from "./testing.js"; import { boardReducer } from "./boardReducer.js"; const cards = [ { id: 1, title: "Read", column: "todo", minutes: 20 }, { id: 2, title: "Build", column: "doing", minutes: 30 }, ]; test("card_added adds a card to To do", () => { const next = boardReducer(cards, { type: "card_added", id: 3, title: "Test", minutes: 15 }); expectEqual(next.length, 3); expectEqual(next[2], { id: 3, title: "Test", column: "todo", minutes: 15 }); }); test("card_added leaves the old array alone", () => { boardReducer(cards, { type: "card_added", id: 3, title: "Test", minutes: 15 }); expectEqual(cards.length, 2); }); test("card_moved changes only that card's column", () => { const next = boardReducer(cards, { type: "card_moved", id: 1, column: "done" }); expectEqual(next.map((card) => card.column), ["done", "doing"]); }); // A tiny test runner, so tests can run in the lab. On your own computer you'd // use Vitest, which works the same way: named tests and expectations. export const results = []; export function test(name, fn) { try { fn(); results.push({ name, passed: true }); } catch (error) { results.push({ name, passed: false, message: error.message }); } } export function expectEqual(actual, expected) { const a = JSON.stringify(actual); const e = JSON.stringify(expected); if (a !== e) throw new Error(`Expected ${e}, got ${a}`); } body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.
Hint 1: the idea

next.map((card) => card.id) gives a short array that's easy to compare, such as [2].

Hint 2: a first step

Dispatch card_removed with id: 99, and expect the ids to be [1, 2].

Show one solution
JavaScript
test("card_removed removes only that card", () => {
  const next = boardReducer(cards, { type: "card_removed", id: 1 });
  expectEqual(next.map((card) => card.id), [2]);
});

test("card_removed with an unknown id changes nothing", () => {
  const next = boardReducer(cards, { type: "card_removed", id: 99 });
  expectEqual(next.map((card) => card.id), [1, 2]);
});

The page then shows All 6 tests pass, counting the one you added above.

Was this article helpful?

Your response is saved on this device.