Skip to content

Checkpoint: A Tested Flashcard Reducer

The Course
•
20 min study

Close the earlier lessons and build this from the brief. The starter already has the screen and one failing test. You write deckReducer and the rest of the tests.

The brief

The deck's state is { cards, index, right, seen }. Write deckReducer in deckReducer.js with two actions:

ActionEffect
{ type: "card_answered", correct }Moves to the next card, back to the first after the last. Adds 1 to seen, and to right when correct is true.
{ type: "deck_restarted" }Sets index, right and seen back to 0. Keeps the cards.

Any other action throws Unknown action: <type>.

Then add tests to deckReducer.test.js for:

  1. a wrong answer;
  2. wrapping round after the last card;
  3. restarting;
  4. the reducer leaving the deck it was given unchanged;
  5. an unknown action throwing that message.

Acceptance checks:

  • The page shows All 6 tests pass.
  • Breaking any one rule in your reducer makes at least one test fail.
Your workspace React · 7 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useReducer } from "react"; import { deckReducer, initialDeck } from "./deckReducer.js"; import Tests from "./Tests.jsx"; export default function App() { const [deck, dispatch] = useReducer(deckReducer, initialDeck); const card = deck.cards[deck.index]; return ( <main> <h1>Flashcards</h1> <section className="panel"> <p className="muted">Card {deck.index + 1} of {deck.cards.length}</p> <h2>{card.question}</h2> <p>{card.answer}</p> <button onClick={() => dispatch({ type: "card_answered", correct: true })}>I got it</button>{" "} <button onClick={() => dispatch({ type: "card_answered", correct: false })}>I missed it</button>{" "} <button onClick={() => dispatch({ type: "deck_restarted" })}>Restart</button> <p>{deck.right} of {deck.seen} right</p> </section> <Tests /> </main> ); } export const initialDeck = { cards: [ { question: "What does useReducer return?", answer: "The state and a dispatch function" }, { question: "What must a reducer never do?", answer: "Change its arguments" }, { question: "What should an unknown action do?", answer: "Throw an error" }, ], index: 0, right: 0, seen: 0, }; // Write the reducer here. See the brief for the two actions. export function deckReducer(deck, action) { return deck; } import { test, expectEqual } from "./testing.js"; import { deckReducer, initialDeck } from "./deckReducer.js"; test("a right answer counts and moves to the next card", () => { const next = deckReducer(initialDeck, { type: "card_answered", correct: true }); expectEqual([next.index, next.right, next.seen], [1, 1, 1]); }); // Add the other tests from the brief here. // 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}`); } import { results } from "./testing.js"; import "./deckReducer.test.js"; export default function Tests() { const failed = results.filter((r) => !r.passed).length; return ( <section className="panel"> <h2>{failed === 0 ? `All ${results.length} tests pass` : `${failed} of ${results.length} tests fail`}</h2> <ul className="cards"> {results.map((r) => ( <li key={r.name}> {r.passed ? "✓" : "✗"} {r.name} {!r.passed && <div className="error">{r.message}</div>} </li> ))} </ul> </section> ); } 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: one new object

Each action returns { ...deck, ... } with the fields that change. cards is never touched.

Hint 2: testing a throw

Call the reducer inside try, store error.message in catch, then expectEqual the message. Start the variable as "no error", so a reducer that doesn't throw fails the test.

Show one solution
One solution React · 7 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useReducer } from "react"; import { deckReducer, initialDeck } from "./deckReducer.js"; import Tests from "./Tests.jsx"; export default function App() { const [deck, dispatch] = useReducer(deckReducer, initialDeck); const card = deck.cards[deck.index]; return ( <main> <h1>Flashcards</h1> <section className="panel"> <p className="muted">Card {deck.index + 1} of {deck.cards.length}</p> <h2>{card.question}</h2> <p>{card.answer}</p> <button onClick={() => dispatch({ type: "card_answered", correct: true })}>I got it</button>{" "} <button onClick={() => dispatch({ type: "card_answered", correct: false })}>I missed it</button>{" "} <button onClick={() => dispatch({ type: "deck_restarted" })}>Restart</button> <p>{deck.right} of {deck.seen} right</p> </section> <Tests /> </main> ); } export const initialDeck = { cards: [ { question: "What does useReducer return?", answer: "The state and a dispatch function" }, { question: "What must a reducer never do?", answer: "Change its arguments" }, { question: "What should an unknown action do?", answer: "Throw an error" }, ], index: 0, right: 0, seen: 0, }; export function deckReducer(deck, action) { switch (action.type) { case "card_answered": return { ...deck, index: (deck.index + 1) % deck.cards.length, right: deck.right + (action.correct ? 1 : 0), seen: deck.seen + 1, }; case "deck_restarted": return { ...deck, index: 0, right: 0, seen: 0 }; default: throw new Error(`Unknown action: ${action.type}`); } } import { test, expectEqual } from "./testing.js"; import { deckReducer, initialDeck } from "./deckReducer.js"; test("a right answer counts and moves to the next card", () => { const next = deckReducer(initialDeck, { type: "card_answered", correct: true }); expectEqual([next.index, next.right, next.seen], [1, 1, 1]); }); test("a wrong answer counts as seen but not right", () => { const next = deckReducer(initialDeck, { type: "card_answered", correct: false }); expectEqual([next.index, next.right, next.seen], [1, 0, 1]); }); test("after the last card, the deck goes back to the first", () => { const last = { ...initialDeck, index: 2 }; expectEqual(deckReducer(last, { type: "card_answered", correct: true }).index, 0); }); test("deck_restarted resets the position and the score", () => { const played = { ...initialDeck, index: 2, right: 1, seen: 2 }; const next = deckReducer(played, { type: "deck_restarted" }); expectEqual([next.index, next.right, next.seen], [0, 0, 0]); }); test("the reducer doesn't change the deck it was given", () => { deckReducer(initialDeck, { type: "card_answered", correct: true }); expectEqual([initialDeck.index, initialDeck.right, initialDeck.seen], [0, 0, 0]); }); test("an unknown action throws", () => { let message = "no error"; try { deckReducer(initialDeck, { type: "card_flipped" }); } catch (error) { message = error.message; } expectEqual(message, "Unknown action: card_flipped"); }); // 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}`); } import { results } from "./testing.js"; import "./deckReducer.test.js"; export default function Tests() { const failed = results.filter((r) => !r.passed).length; return ( <section className="panel"> <h2>{failed === 0 ? `All ${results.length} tests pass` : `${failed} of ${results.length} tests fail`}</h2> <ul className="cards"> {results.map((r) => ( <li key={r.name}> {r.passed ? "✓" : "✗"} {r.name} {!r.passed && <div className="error">{r.message}</div>} </li> ))} </ul> </section> ); } 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.

Check yourself

  1. What does a reducer take, and what does it return?
  2. Why does Date.now() belong in the event handler and not the reducer?
  3. A switch case forgets its return. What happens?

Was this article helpful?

Your response is saved on this device.