Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Routing and Application Architecture
Stage 5: Specialization (pick ONE)

Part 14 / Stage 3

Testing React components

Goal: Make testing a first-class topic instead of something this course has only ever done implicitly. Know Testing Library's query priority and why getByRole comes first, when user-event behaves differently from fireEvent and why that difference is real, the right async tool for the right shape of "wait for this," fake timers, the two ways to test a hook, what a test should never look at, and how to arrange test data without copy-pasting the same object into every test. Time: ~5 hours ยท Level: has written and run Vitest + Testing Library tests since Part 1, without this course ever naming the rules behind them until now

What you will learn

  • Testing Library's query priority order, and why getByRole is ranked first - it is the one query that matches what an actual user, sighted or using a screen reader, can perceive and act on
  • user-event vs fireEvent: fireEvent is a thin wrapper around dispatchEvent, user-event drives the same sequence of real events (and the browser's own input constraints) a real keystroke or click would - a difference you can watch happen, not just a style preference
  • findBy* (sugar for "retry a getBy* query inside waitFor") vs waitFor (the general tool, for anything that is not itself a DOM query, like a mock's call count) vs waitForElementToBeRemoved
  • Fake timers: vi.useFakeTimers(), vi.advanceTimersByTime(), and why a timer-driven setState has to be wrapped in act()
  • Two ways to test a hook: through a real consuming component (the default, whenever one naturally exists) and renderHook (for exercising a hook's own contract directly, with no UI standing in the way)
  • What a test should never query: implementation details like an internal CSS class name or a specific piece of internal state - proven by refactoring a component's internals and watching a behaviour-based test survive while an implementation-detail-based one would not
  • Arranging test data with a small factory function (makeThing(overrides)) instead of a slightly-different literal object copy-pasted into every test

A note this part exists to make explicit: every example and solution test file since Part 1 already used render, screen, Vitest matchers, and - from Part 6 onward - fireEvent/userEvent/vi.useFakeTimers. This part is not introducing a new skill from zero; it is naming the rules this course's own test suite has been quietly following the whole time, and in a few places below, pointing straight at the real file where you already saw the pattern.

Topics in this part

Practice

Every exercise below is a real, runnable .jsx (or, for Exercise 1, a plain .js reducer) paired with a .test.jsx that actually renders/calls it using Vitest and Testing Library - the same verified-output rule as every example in this course. No exercise makes a real network call: Exercise 4 stubs fetch itself, the same way examples/03_async_findby_waitfor.test.jsx does.


Exercise 1: A reducer tested in complete isolation

Scenario: A Swiggy-style cart reducer needs coverage that has nothing to do with rendering at all - a reducer is a plain function, (state, action) => newState, and the fastest, most direct test of one never touches render or screen. What to do: Write cartReducer(state, action) in a plain .js file (no JSX, no React import) supporting three actions: { type: "add", item } (adds a new item at quantity 1, or increments an existing item's quantity by matching id), { type: "remove", id } (drops that item entirely), and { type: "clear" } (empties the cart). Keep state shaped { items: [...], total }, with total recomputed on every action. Test it by calling cartReducer(state, action) directly and asserting on the object it returns - no render, no component, nothing from @testing-library/react at all.

Sample output (really run):

cartReducer({ items: [], total: 0 }, { type: "add", item: { id: "p1", name: "Samosa", price: 20 } })
  -> { items: [{ id: "p1", name: "Samosa", price: 20, qty: 1 }], total: 20 }

cartReducer(<same state again>, { type: "add", item: { id: "p1", name: "Samosa", price: 20 } })
  -> qty becomes 2, total becomes 40 - same item, not a duplicate row

cartReducer(<cart with 2 items>, { type: "clear" })
  -> { items: [], total: 0 }

๐Ÿ’ก Hint: nothing here needs @testing-library/react - a reducer's contract is "given this state and this action, return this new state," and the most direct test of that contract is calling the function and asserting on its return value, the same way you would test any other plain function.


Exercise 2: Fix a query-priority bug caused by a harmless refactor

Scenario: An Ola-style "Confirm pickup point" form was first written - and first tested - leaning on data-testid and a CSS class, exactly the anti-pattern Section 1 and the Common Mistakes table warn about:

export function PickupConfirmFormV1({ onConfirm }) {
  const [address, setAddress] = useState("");
  return (
    <form onSubmit={(e) => { e.preventDefault(); onConfirm(address); }}>
      <label>Pickup address
        <input data-testid="pickup-input" value={address} onChange={(e) => setAddress(e.target.value)} />
      </label>
      <button type="submit" className="confirm-btn" data-testid="confirm-btn">Confirm</button>
    </form>
  );
}

A teammate then ships a harmless visual refactor, PickupConfirmFormV2 - same markup shape, same behaviour, but every data-testid and the className are gone (a new design-system <Button> no longer accepts arbitrary classes). What to do: Write both components (V1 exactly as above, V2 with the test ids and class removed but the same real <label> and the same accessible button text, "Confirm"). Write one test file with two describe blocks: one proving a getByTestId("confirm-btn")/container.querySelector(".confirm-btn")-based test passes against V1 and fails to find anything against V2; a second proving a getByLabelText("Pickup address") + getByRole("button", { name: "Confirm" })-based test passes against both versions unchanged.

Sample output (really run):

brittle query on V1: finds the button fine
brittle query on V2: container.querySelector(".confirm-btn") is null - nothing to find, same button, same behaviour
resilient query on V1: finds the label and the button
resilient query on V2: finds the exact same label and button - the query never depended on what changed

๐Ÿ’ก Hint: this is example 06's refactor-and-watch method, aimed at Section 1's query-priority rule instead of Section 6's implementation-detail rule - same experiment, different thing being proven.


Exercise 3: user-event vs fireEvent on a real input constraint

Scenario: A Swiggy/Ola-style login screen's mobile-number field is a plain <input maxLength={10} ... /> - the browser's own constraint is the only thing stopping an 11th digit, exactly like examples/02_user_event_vs_fire_event.jsx's OTP field, just a different field. What to do: Write MobileNumberInput() with aria-label="Mobile number" and maxLength={10}. Write a test proving fireEvent.change(input, { target: { value: "98765432109" } }) really leaves all 11 digits in the input (maxLength never gets consulted because nothing resembling a keystroke happened), and a second test proving userEvent.type(input, "98765432109") really stops at 10 digits - "9876543210" - the same clamp a real browser applies to real typing.

Sample output (really run):

fireEvent.change with "98765432109" -> input value is "98765432109" (all 11 digits - maxLength bypassed)
userEvent.type with "98765432109"   -> input value is "9876543210" (10 digits - maxLength respected)

๐Ÿ’ก Hint: this is examples/02_user_event_vs_fire_event.test.jsx's exact pair of assertions, on a differently-named field - the point is to reproduce the gotcha yourself, not to invent a new one.


Exercise 4: An async loading -> success/error delivery tracker

Scenario: A Zomato-style delivery tracker needs to show "Tracking order..." while a fetch is in flight, then either the rider's distance or an error, with no real network call in the test. What to do: Write DeliveryTracker({ orderId }) using the same one-modeled-state shape as examples/03_async_findby_waitfor.jsx's WalletBalance: useState({ phase: "loading" }), fetching `/api/orders/${orderId}/track` inside a useEffect keyed on orderId. Render "Tracking order..." while loading, <p role="alert">{message}</p> on error, and `Rider is ${data.distanceKm} km away` on success. Write tests for: (1) the success path, asserting the loading text first and then using findByText for the resolved distance text; (2) the error path, using findByRole("alert"); (3) a waitFor assertion on the mocked fetch's call count (not a DOM query) proving it was called exactly once with the right URL.

Sample output (really run, orderId="ZO-9981"):

first render           -> "Tracking order..."
fetch resolves success -> "Rider is 2 km away"       (found with findByText)
fetch resolves failure -> role="alert", "could not track order"  (found with findByRole)
waitFor                -> fetchMock called exactly once, with "/api/orders/ZO-9981/track"

๐Ÿ’ก Hint: this is WalletBalance with a tracking message instead of a balance - the same vi.stubGlobal("fetch", ...) plus vi.unstubAllGlobals() in afterEach shape as examples/03_async_findby_waitfor.test.jsx.


Exercise 5: A fake-timers "resend OTP" cooldown button

Scenario: An IRCTC/Ola-style login screen disables its "Resend OTP" button for 30 real seconds after each send - a real test should not sit and wait 30 real seconds for that, once per run, forever. What to do: Write ResendOtpButton({ cooldownSeconds = 30, onResend }): a useState counting down from cooldownSeconds, ticking every 1000ms via setInterval inside a useEffect, cleared on unmount. While the count is above 0, render a disabled button labelled `Resend OTP in ${secondsLeft}s`; once it reaches 0, render an enabled button labelled "Resend OTP" that calls onResend when clicked. Write a test file with beforeEach/afterEach installing and restoring vi.useFakeTimers()/vi.useRealTimers() (the same shape as examples/04_fake_timers.test.jsx), proving: the button is disabled and still counting down after 29 of the 30 seconds (wrapped in act()), it becomes enabled the instant the 30th second passes, and clicking it afterwards really calls onResend (via userEvent, after first switching back to real timers for that one interaction, or via fireEvent.click while still on fake timers).

Sample output (really run):

t = 0s      -> disabled, "Resend OTP in 30s"
t = 29s     -> disabled, "Resend OTP in 1s"
t = 30s     -> enabled, "Resend OTP"
click it    -> onResend called exactly once

๐Ÿ’ก Hint: every vi.advanceTimersByTime(...) that is expected to cause a re-render needs an act() wrapper around it, exactly like Section 4 and examples/04_fake_timers.test.jsx - and do not forget the afterEach(() => vi.useRealTimers()), or the next test file to run may inherit a frozen clock.


Exercise 6: A clamped useVolumeLevel hook, tested two ways

Scenario: A BookMyShow/OTT-style in-app volume control needs a hook clamped on both ends (0 and 10, not just a floor like examples/05...jsx's cart quantity) - and this exercise exists specifically to make you hit the renderHook/rerender gotcha from README Section 5 yourself, not just read about it. What to do: Write useVolumeLevel(initial = 5, { min = 0, max = 10 } = {}), returning { level, increase, decrease }, with increase/decrease clamped at max/min respectively. Write VolumeControl(), an ordinary consumer with "+"/"-" buttons and the current level displayed as text. Write one test file with two describe blocks: the first renders VolumeControl and proves, via real clicks, that it clamps at both 10 and 0; the second uses renderHook(({ initial }) => useVolumeLevel(initial), { initialProps: { initial: 5 } }) directly, proves increase/decrease work on result.current (wrapped in act()), and then proves the Section 5 gotcha itself: after a few increase() calls move level away from 5, calling rerender({ initial: 8 }) does not reset level to 8, because useState's initial argument is only read on the hook's very first render.

Sample output (really run):

VolumeControl: clicking "+" ten times from level 5 stops at 10, not 15
VolumeControl: clicking "-" from level 0 stays at 0, not -1
renderHook:    increase() twice from initial=5 -> level is 7
renderHook:    rerender({ initial: 8 }) right after -> level is STILL 7, not 8 - the gotcha, reproduced directly

๐Ÿ’ก Hint: this is examples/05_testing_hooks_via_components_and_renderhook.test.jsx's exact rerender experiment, just with a two-sided clamp instead of a floor-only one - write the ceiling-clamp assertion first, it is the one part of this exercise genuinely new relative to the example.

Show the solutions for Part 14 (12 files)

solutions/ex01_cart_reducer.js

// A plain reducer - no React import anywhere in this file, on purpose.
// (state, action) => newState is the whole contract, and the fastest,
// most direct way to test that contract is calling the function and
// asserting on what it returns - no render, no screen, nothing from
// @testing-library/react at all. See ex01_cart_reducer.test.jsx.
export const initialCartState = { items: [], total: 0 };

function computeTotal(items) {
  return items.reduce((sum, item) => sum + item.price * item.qty, 0);
}

export function cartReducer(state, action) {
  switch (action.type) {
    case "add": {
      const existing = state.items.find((item) => item.id === action.item.id);
      const items = existing
        ? state.items.map((item) => (item.id === action.item.id ? { ...item, qty: item.qty + 1 } : item))
        : [...state.items, { ...action.item, qty: 1 }];
      return { items, total: computeTotal(items) };
    }
    case "remove": {
      const items = state.items.filter((item) => item.id !== action.id);
      return { items, total: computeTotal(items) };
    }
    case "clear":
      return { items: [], total: 0 };
    default:
      return state;
  }
}

solutions/ex01_cart_reducer.test.jsx

import { describe, test, expect } from "vitest";
import { cartReducer, initialCartState } from "./ex01_cart_reducer.js";

// No `render`, no `screen`, nothing from @testing-library/react at all -
// a reducer is a plain function, and the most direct test of one calls it
// and asserts on its return value. This file's extension is .test.jsx
// only because vite.config.js's `include` glob only looks for
// *.test.jsx - nothing inside it is actually JSX.
const samosa = { id: "p1", name: "Samosa", price: 20 };
const lassi = { id: "p2", name: "Lassi", price: 40 };

describe("cartReducer: add", () => {
  test("adding a new item puts it in at quantity 1", () => {
    const state = cartReducer(initialCartState, { type: "add", item: samosa });
    expect(state.items).toEqual([{ ...samosa, qty: 1 }]);
    expect(state.total).toBe(20);
  });

  test("adding the same item again increments its quantity instead of duplicating the row", () => {
    let state = cartReducer(initialCartState, { type: "add", item: samosa });
    state = cartReducer(state, { type: "add", item: samosa });
    expect(state.items).toEqual([{ ...samosa, qty: 2 }]);
    expect(state.total).toBe(40);
  });

  test("adding a second, different item keeps both rows and sums the total correctly", () => {
    let state = cartReducer(initialCartState, { type: "add", item: samosa });
    state = cartReducer(state, { type: "add", item: lassi });
    expect(state.items).toHaveLength(2);
    expect(state.total).toBe(60);
  });
});

describe("cartReducer: remove", () => {
  test("removing by id drops exactly that item and recomputes the total", () => {
    let state = cartReducer(initialCartState, { type: "add", item: samosa });
    state = cartReducer(state, { type: "add", item: lassi });
    state = cartReducer(state, { type: "remove", id: "p1" });
    expect(state.items).toEqual([{ ...lassi, qty: 1 }]);
    expect(state.total).toBe(40);
  });

  test("removing an id that is not in the cart is a no-op", () => {
    const state = cartReducer(initialCartState, { type: "remove", id: "does-not-exist" });
    expect(state).toEqual(initialCartState);
  });
});

describe("cartReducer: clear", () => {
  test("clear empties the cart and zeroes the total, regardless of what was in it", () => {
    let state = cartReducer(initialCartState, { type: "add", item: samosa });
    state = cartReducer(state, { type: "add", item: lassi });
    state = cartReducer(state, { type: "clear" });
    expect(state).toEqual({ items: [], total: 0 });
  });
});

describe("cartReducer: unknown action", () => {
  test("an action type the reducer does not recognize returns the same state unchanged", () => {
    const state = cartReducer(initialCartState, { type: "not-a-real-action" });
    expect(state).toBe(initialCartState);
  });
});

solutions/ex02_query_priority_refactor.jsx

import { useState } from "react";

// V1: an Ola-style "confirm pickup point" form, first written - and first
// *tested* - leaning on data-testid and a CSS class. Nothing about this is
// broken; it is the anti-pattern Section 1 and the Common Mistakes table
// warn about, written out so the next version's refactor has something
// real to break.
export function PickupConfirmFormV1({ onConfirm }) {
  const [address, setAddress] = useState("");
  return (
    <form
      onSubmit={(e) => {
        e.preventDefault();
        onConfirm(address);
      }}
    >
      <label>
        Pickup address
        <input data-testid="pickup-input" value={address} onChange={(e) => setAddress(e.target.value)} />
      </label>
      <button type="submit" className="confirm-btn" data-testid="confirm-btn">
        Confirm
      </button>
    </form>
  );
}

// V2: a harmless visual refactor six months later - a new design-system
// <Button> no longer accepts arbitrary classes, and nobody bothered
// carrying the data-testid over because nothing on the team's checklist
// asked them to. Same real <label>, same accessible button text
// ("Confirm"), same behaviour a user can see and use - every test id and
// the class are simply gone.
export function PickupConfirmFormV2({ onConfirm }) {
  const [address, setAddress] = useState("");
  return (
    <form
      onSubmit={(e) => {
        e.preventDefault();
        onConfirm(address);
      }}
    >
      <label>
        Pickup address
        <input value={address} onChange={(e) => setAddress(e.target.value)} />
      </label>
      <button type="submit">Confirm</button>
    </form>
  );
}

solutions/ex02_query_priority_refactor.test.jsx

import { describe, test, expect, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { PickupConfirmFormV1, PickupConfirmFormV2 } from "./ex02_query_priority_refactor.jsx";

describe("the brittle way: query by data-testid/CSS class - this is what Section 1 is warning about", () => {
  test("V1's test id and class exist and can be found this way...", () => {
    const { container } = render(<PickupConfirmFormV1 onConfirm={() => {}} />);
    expect(screen.getByTestId("confirm-btn")).toBeInTheDocument();
    expect(container.querySelector(".confirm-btn")).not.toBeNull();
  });

  test("...but the exact same user-visible button in V2 has neither - a test written this way breaks on this refactor, for no real reason", () => {
    const { container } = render(<PickupConfirmFormV2 onConfirm={() => {}} />);
    expect(screen.queryByTestId("confirm-btn")).not.toBeInTheDocument();
    expect(container.querySelector(".confirm-btn")).toBeNull();
    // The button is still right there, findable the resilient way:
    expect(screen.getByRole("button", { name: "Confirm" })).toBeInTheDocument();
  });
});

describe("the resilient way: query by role and label text - survives the refactor unchanged", () => {
  test.each([
    ["V1", PickupConfirmFormV1],
    ["V2", PickupConfirmFormV2],
  ])("%s: the address field and the confirm button are both findable without any test id or class", (_label, Form) => {
    render(<Form onConfirm={() => {}} />);
    expect(screen.getByLabelText("Pickup address")).toBeInTheDocument();
    expect(screen.getByRole("button", { name: "Confirm" })).toBeInTheDocument();
  });

  test.each([
    ["V1", PickupConfirmFormV1],
    ["V2", PickupConfirmFormV2],
  ])("%s: typing an address and submitting calls onConfirm with it, found and driven entirely by role/label", async (_label, Form) => {
    const user = userEvent.setup();
    const onConfirm = vi.fn();
    render(<Form onConfirm={onConfirm} />);

    await user.type(screen.getByLabelText("Pickup address"), "MG Road Metro Gate 2");
    await user.click(screen.getByRole("button", { name: "Confirm" }));

    expect(onConfirm).toHaveBeenCalledWith("MG Road Metro Gate 2");
  });
});

solutions/ex03_mobile_number_input.jsx

import { useState } from "react";

// A Swiggy/Ola-style login screen's mobile-number field - the browser's
// own `maxLength` is the only thing stopping an 11th digit, exactly like
// examples/02_user_event_vs_fire_event.jsx's OTP field, just a different
// real-world field with the same real-world constraint.
export function MobileNumberInput() {
  const [value, setValue] = useState("");
  return <input aria-label="Mobile number" maxLength={10} value={value} onChange={(e) => setValue(e.target.value)} />;
}

solutions/ex03_mobile_number_input.test.jsx

import { describe, test, expect } from "vitest";
import { render, screen, fireEvent } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { MobileNumberInput } from "./ex03_mobile_number_input.jsx";

// Same gotcha as examples/02_user_event_vs_fire_event.test.jsx, reproduced
// on a different real field: fireEvent.change sets .value directly and
// never consults the browser's own maxLength machinery; userEvent.type
// drives real keystrokes, through the same path maxLength actually
// enforces against.
describe("fireEvent.change vs userEvent.type on a 10-digit mobile number field", () => {
  test("fireEvent.change bypasses maxLength completely", () => {
    render(<MobileNumberInput />);
    const input = screen.getByLabelText("Mobile number");

    fireEvent.change(input, { target: { value: "98765432109" } });

    expect(input).toHaveValue("98765432109");
  });

  test("userEvent.type respects maxLength, the same way a real keystroke in a real browser would", async () => {
    const user = userEvent.setup();
    render(<MobileNumberInput />);
    const input = screen.getByLabelText("Mobile number");

    await user.type(input, "98765432109");

    expect(input).toHaveValue("9876543210");
  });
});

solutions/ex04_delivery_tracker.jsx

import { useEffect, useState } from "react";

// A Zomato-style delivery tracker - the same "one modeled state" shape as
// examples/03_async_findby_waitfor.jsx's WalletBalance, fetching a
// different thing.
export function DeliveryTracker({ orderId }) {
  const [state, setState] = useState({ phase: "loading" });

  useEffect(() => {
    setState({ phase: "loading" });
    fetch(`/api/orders/${orderId}/track`)
      .then((res) => (res.ok ? res.json() : Promise.reject(new Error("could not track order"))))
      .then((data) => setState({ phase: "success", data }))
      .catch((error) => setState({ phase: "error", message: error.message }));
  }, [orderId]);

  if (state.phase === "loading") return <p>Tracking order...</p>;
  if (state.phase === "error") return <p role="alert">{state.message}</p>;
  return <p>Rider is {state.data.distanceKm} km away</p>;
}

solutions/ex04_delivery_tracker.test.jsx

import { describe, test, expect, vi, afterEach } from "vitest";
import { render, screen, waitFor } from "@testing-library/react";
import { DeliveryTracker } from "./ex04_delivery_tracker.jsx";

afterEach(() => {
  vi.unstubAllGlobals();
});

function fakeFetch(result) {
  vi.stubGlobal(
    "fetch",
    vi.fn(() => Promise.resolve(result))
  );
}

describe("DeliveryTracker: findBy* for the two resolved states", () => {
  test("shows the loading text first, then the rider's distance once the fetch resolves", async () => {
    fakeFetch({ ok: true, json: () => Promise.resolve({ distanceKm: 2 }) });
    render(<DeliveryTracker orderId="ZO-9981" />);

    expect(screen.getByText("Tracking order...")).toBeInTheDocument();
    expect(await screen.findByText("Rider is 2 km away")).toBeInTheDocument();
  });

  test("shows the alert role once a failed fetch resolves", async () => {
    fakeFetch({ ok: false });
    render(<DeliveryTracker orderId="ZO-9981" />);

    expect(await screen.findByRole("alert")).toHaveTextContent("could not track order");
  });
});

describe("DeliveryTracker: waitFor for the mock's call count, not a DOM query", () => {
  test("fetch was really called exactly once, with the right URL", async () => {
    const fetchMock = vi.fn(() => Promise.resolve({ ok: true, json: () => Promise.resolve({ distanceKm: 5 }) }));
    vi.stubGlobal("fetch", fetchMock);
    render(<DeliveryTracker orderId="ZO-9981" />);

    await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
    expect(fetchMock).toHaveBeenCalledWith("/api/orders/ZO-9981/track");
  });
});

solutions/ex05_resend_otp_button.jsx

import { useEffect, useState } from "react";

// An IRCTC/Ola-style "Resend OTP" button - disabled for `cooldownSeconds`
// real seconds after it mounts, exactly the kind of component a real test
// should never actually sit and wait out.
//
// One interval is created for the whole cooldown (keyed only on
// `cooldownSeconds`, not on the countdown itself), decremented with a
// functional update, and it clears itself the moment it reaches 0 - so
// there is exactly one timer in flight at any point, never recreated on
// every tick.
export function ResendOtpButton({ cooldownSeconds = 30, onResend }) {
  const [secondsLeft, setSecondsLeft] = useState(cooldownSeconds);

  useEffect(() => {
    const timer = setInterval(() => {
      setSecondsLeft((s) => {
        if (s <= 1) {
          clearInterval(timer);
          return 0;
        }
        return s - 1;
      });
    }, 1000);
    return () => clearInterval(timer);
  }, [cooldownSeconds]);

  if (secondsLeft > 0) {
    return <button disabled>Resend OTP in {secondsLeft}s</button>;
  }
  return <button onClick={onResend}>Resend OTP</button>;
}

solutions/ex05_resend_otp_button.test.jsx

import { describe, test, expect, vi, beforeEach, afterEach } from "vitest";
import { render, screen, act, fireEvent } from "@testing-library/react";
import { ResendOtpButton } from "./ex05_resend_otp_button.jsx";

beforeEach(() => {
  vi.useFakeTimers();
});

afterEach(() => {
  // Always restore real timers, even if a test fails - a fake-timer leak
  // into the next test file is exactly the confusing, unrelated-looking
  // failure Section 4 warns about.
  vi.useRealTimers();
});

describe("ResendOtpButton, on a fake clock instead of a real 30-second wait", () => {
  test("stays disabled and counting down right up to the last second", () => {
    render(<ResendOtpButton onResend={vi.fn()} />);
    expect(screen.getByRole("button", { name: "Resend OTP in 30s" })).toBeDisabled();

    act(() => {
      vi.advanceTimersByTime(29000);
    });
    expect(screen.getByRole("button", { name: "Resend OTP in 1s" })).toBeDisabled();
  });

  test("becomes enabled the instant the cooldown passes - not a moment before", () => {
    render(<ResendOtpButton onResend={vi.fn()} />);

    act(() => {
      vi.advanceTimersByTime(29999);
    });
    expect(screen.getByRole("button", { name: "Resend OTP in 1s" })).toBeDisabled();

    act(() => {
      vi.advanceTimersByTime(1);
    });
    expect(screen.getByRole("button", { name: "Resend OTP" })).toBeEnabled();
  });

  test("clicking the enabled button really calls onResend", () => {
    const onResend = vi.fn();
    render(<ResendOtpButton onResend={onResend} />);

    act(() => {
      vi.advanceTimersByTime(30000);
    });
    const button = screen.getByRole("button", { name: "Resend OTP" });

    // fireEvent, not user-event, on purpose: user-event's own internal
    // delays are real-timer-based unless explicitly configured otherwise,
    // and this test's whole point is the countdown, not the click itself -
    // a single fireEvent.click is exactly enough here (Section 2's rule).
    fireEvent.click(button);
    expect(onResend).toHaveBeenCalledTimes(1);
  });

  test("a shorter cooldownSeconds really changes when it re-enables, not just whether it eventually does", () => {
    render(<ResendOtpButton cooldownSeconds={5} onResend={vi.fn()} />);
    expect(screen.getByRole("button", { name: "Resend OTP in 5s" })).toBeDisabled();

    act(() => {
      vi.advanceTimersByTime(4000);
    });
    expect(screen.getByRole("button", { name: "Resend OTP in 1s" })).toBeDisabled();

    act(() => {
      vi.advanceTimersByTime(1000);
    });
    expect(screen.getByRole("button", { name: "Resend OTP" })).toBeEnabled();
  });
});

solutions/ex06_volume_level_hook.jsx

import { useState } from "react";

// A BookMyShow/OTT-style in-app volume control, clamped on BOTH ends -
// unlike examples/05...jsx's cart quantity, which only clamps a floor.
export function useVolumeLevel(initial = 5, { min = 0, max = 10 } = {}) {
  const [level, setLevel] = useState(initial);
  const increase = () => setLevel((l) => Math.min(max, l + 1));
  const decrease = () => setLevel((l) => Math.max(min, l - 1));
  return { level, increase, decrease };
}

// An ordinary consumer - most of this hook's real coverage should come
// from testing this, because this is how it is actually used.
export function VolumeControl() {
  const { level, increase, decrease } = useVolumeLevel(5);
  return (
    <div>
      <button onClick={decrease}>-</button>
      <span>Volume: {level}</span>
      <button onClick={increase}>+</button>
    </div>
  );
}

solutions/ex06_volume_level_hook.test.jsx

import { describe, test, expect } from "vitest";
import { render, screen, renderHook, act } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { useVolumeLevel, VolumeControl } from "./ex06_volume_level_hook.jsx";

describe("via a real component - preferred whenever the hook has an obvious consumer", () => {
  test("clicking '+' ten times from level 5 stops at 10, not 15 - the ceiling clamp", async () => {
    const user = userEvent.setup();
    render(<VolumeControl />);

    expect(screen.getByText("Volume: 5")).toBeInTheDocument();
    for (let i = 0; i < 10; i++) {
      await user.click(screen.getByRole("button", { name: "+" }));
    }
    expect(screen.getByText("Volume: 10")).toBeInTheDocument();
  });

  test("clicking '-' past 0 stays at 0, not -1 - the floor clamp", async () => {
    const user = userEvent.setup();
    render(<VolumeControl />);

    for (let i = 0; i < 10; i++) {
      await user.click(screen.getByRole("button", { name: "-" }));
    }
    expect(screen.getByText("Volume: 0")).toBeInTheDocument();
  });
});

describe("via renderHook - for exercising the hook's own contract directly, with no UI in the way", () => {
  test("increase/decrease behave correctly on result.current, clamped at both ends", () => {
    const { result } = renderHook(() => useVolumeLevel(5));

    expect(result.current.level).toBe(5);

    act(() => result.current.increase());
    act(() => result.current.increase());
    expect(result.current.level).toBe(7);

    for (let i = 0; i < 10; i++) {
      act(() => result.current.decrease());
    }
    expect(result.current.level).toBe(0); // floor clamp, exercised directly

    for (let i = 0; i < 12; i++) {
      act(() => result.current.increase());
    }
    expect(result.current.level).toBe(10); // ceiling clamp, exercised directly
  });

  test("rerender does NOT reset an already-running hook's level - useState's initial argument is only read once", () => {
    const { result, rerender } = renderHook(({ initial }) => useVolumeLevel(initial), {
      initialProps: { initial: 5 },
    });
    expect(result.current.level).toBe(5);

    act(() => result.current.increase());
    act(() => result.current.increase());
    expect(result.current.level).toBe(7);

    // This is Section 5's gotcha, reproduced directly: changing `initial`
    // does not reset the hook's own state - useState only reads its
    // initial argument on the very first render, exactly like Part 10's
    // lazy-init distinction for useReducer, seen again here from the test
    // side.
    rerender({ initial: 8 });
    expect(result.current.level).toBe(7); // still 7, NOT reset to 8
  });
});

Going deeper: screen.debug() and testing an error boundary

Two things worth knowing that do not fit neatly under any one numbered section above, because they come up while debugging a failing test rather than while writing a passing one.

screen.debug() - what is actually in the DOM, right now. Every query above throws its own reasonably helpful error on failure, but the fastest way to actually see what Testing Library sees - not what you assume is there - is screen.debug(): it pretty-prints the current DOM to the console, exactly as render left it, with no guessing. Reach for it the moment a query you are sure should match does not: a loading state that has not resolved yet, text split across two elements (getByText by default only matches a single node's text content), or a label whose accessible name is not quite the string you typed. screen.debug(element) (passed a specific element instead of nothing) narrows the printout to just that subtree, which matters once a page's markup gets large enough that the full dump is more noise than signal. None of this is a new API to learn for this part specifically - it has been sitting on screen the entire time, next to every getByRole/findByText this course has used since Part 1 - it is just never been named until now.

Testing an error boundary: expect console.error, and mock it on purpose. stage-3-advanced/part-13-error-boundaries-and-code-splitting/examples/02_class_error_boundary_with_fallback.test.jsx throws a real error into a real ErrorBoundary on purpose, inside tests like "a cancelled order throws during render, and the fallback - not a blank screen - is what the user sees". React logs every caught error to console.error whether or not an onError prop is wired up to do anything with it - that is React's own behaviour, not a bug in the component under test, and it would otherwise print a scary-looking stack trace into an otherwise fully green test run. That test file's fix is vi.spyOn(console, "error").mockImplementation(() => {}), paired with vi.restoreAllMocks() in afterEach so the mock does not leak into unrelated tests that might want to see a real console.error (for instance, a test that asserts something was correctly logged). The rule this generalizes: a test that deliberately triggers expected console noise should silence it deliberately, with a spy it also deliberately restores - not leave it printing, and not reach for a global, repo-wide console mock that would hide a real, unexpected error from some other test too.

Common mistakes

Mistake Why it is wrong Fix
Reaching for getByTestId (or container.querySelector) as the first query, because it is the easiest to add It tests nothing a real user or assistive technology could perceive, and breaks on harmless internal refactors that change nothing a user sees (Section 6) Start from getByRole, fall back down Testing Library's priority list only when a role-based query genuinely cannot express what you need (Section 1)
Assuming fireEvent and user-event are interchangeable, just different import names fireEvent skips the browser's own input constraints (maxLength, and others); user-event drives the real event sequence those constraints depend on Default to user-event; use fireEvent deliberately, only when a single low-level event is genuinely all a test needs (Section 2)
Reaching for waitFor to wait for a piece of text, when findByText already does exactly that More code for the same result, and loses the one-step "get it, or fail with a clear message" behaviour findBy* already gives a DOM query Use findBy* whenever the thing you are waiting for is itself a query; save waitFor for things that are not, like a mock's call count (Section 3)
Advancing fake timers without wrapping the call in act() The timer callback's setState can finish after the assertion already ran, making the very next assertion flaky or simply wrong Wrap vi.advanceTimersByTime(...) in act() whenever it is expected to trigger a re-render (Section 4)
Forgetting vi.useRealTimers() in afterEach after a fake-timers test A leaked fake clock keeps running into whatever test or file executes next, producing a confusing, seemingly unrelated failure Always pair vi.useFakeTimers() in beforeEach with vi.useRealTimers() in afterEach (Section 4)
Testing a hook only through renderHook, even when a real consuming component already exists Misses whatever that component's own markup/behaviour contributes - a clamp, a disabled state, a class - and tests a contract no real code actually calls the hook through Default to testing through the real component; reach for renderHook specifically for a hook's own internal contract, in isolation (Section 5)
One slightly-different literal test-data object, copy-pasted into every test in a growing file Every later field added to that shape means hand-editing every copy, and it gets easy to miss one A small makeThing(overrides) factory - override only what a given test actually cares about (Section 7)
Letting a deliberately-triggered console.error (from an error-boundary test, for instance) print on every run, or silencing console.error globally for the whole suite to avoid it A printed-but-ignored stack trace trains everyone to stop reading test output closely; a global mock hides a real, unexpected error in some unrelated test just as effectively as it hides the expected one vi.spyOn(console, "error").mockImplementation(() => {}) for the one test that expects it, restored with vi.restoreAllMocks() in afterEach (Going deeper)

Quick recap

  • Testing Library ranks queries by how close they get to what a real user perceives: getByRole first, getByTestId last - this course's own tests have followed that order since Part 1, this part just names it.
  • fireEvent is a thin, single-event wrapper around dispatchEvent; user-event drives the full, realistic event sequence a real interaction would, including the browser's own input constraints - default to user-event, reach for fireEvent on purpose.
  • findBy* is sugar for "retry a getBy* query inside waitFor" - use it for queries; use waitFor itself for anything that is not a query, like a mock's call count.
  • Fake timers (vi.useFakeTimers/vi.advanceTimersByTime) need act() around any advance that triggers a re-render, and vi.useRealTimers() in afterEach every time, with no exceptions.
  • Test a hook through a real consuming component by default; reach for renderHook to exercise the hook's own contract directly, remembering its initial arguments are only read on the very first render.
  • Never query an implementation detail (an internal CSS class, a specific state shape) - a behaviour-based query survives a harmless refactor that an implementation-detail-based one would not, provable by actually doing the refactor.
  • A small makeThing(overrides) factory keeps a growing test file's "arrange" step from turning into dozens of copy-pasted, slightly-different literal objects.

Checklist

  • I can recite Testing Library's query priority order and say, in one sentence, why getByRole is ranked above getByTestId.
  • I reproduced the maxLength gotcha myself - watched fireEvent.change bypass it and userEvent.type respect it, on the same component.
  • I wrote a test using findBy* for a query and a separate one using waitFor for something that was not a query, and can say why I picked each.
  • I wrote a fake-timers test with vi.useFakeTimers/vi.advanceTimersByTime wrapped in act(), and a matching afterEach that restores real timers.
  • I tested the same hook two ways - through a real consuming component, and with renderHook - and can say when each is the right call.
  • I proved Section 6's claim myself: refactored a component's internals, and watched a behaviour-based test survive while an implementation-detail-based query stopped finding anything.
  • I wrote a makeThing(overrides) factory for at least one test file and used it across more than one test with different overrides.
  • I used screen.debug() at least once to see what Testing Library actually sees, instead of guessing why a query was not matching.
  • I wrote (or read) a test that deliberately triggers a thrown error inside an error boundary, and can say why console.error needs to be mocked and restored around it specifically, not globally.

Search the guide