Skip to content
Tutorials Center
My learning

Topics

Lesson 87 of 132 ยท Testing and Quality

Testing Hooks, Reducers and Custom Logic

Test reducers as plain functions, custom hooks with renderHook, debounced logic with fake timers, fetch with mocks, context with wrappers, and learn when snapshot tests help or hurt.

The previous lesson tested components through their screen output. But a lot of your app's value lives in logic that has no screen of its own: reducers that decide how state changes, custom hooks that wrap timers and network calls, context providers that share the current user. Testing all of that through full components is slow and indirect. Each kind of logic has a better, more direct way to test it.

This lesson moves down the ladder from the simplest to the most React-specific: reducers (plain functions), custom hooks with a renderHook helper, time with fake timers, network with a mocked fetch, context with wrapper components, and finally snapshot tests and their costs. The runnable demos reuse the tiny test harness from the previous lesson (a test runner, render, queries, act); its code is repeated at the top of each example because every example must be self-contained. The only new ingredient is a renderHook function you can read in full.

Real projects use Vitest or Jest with @testing-library/react, which provides renderHook and vi.useFakeTimers() for you. The read-only blocks show those versions. The runnable hand-written versions teach what they do underneath.

Reducers are the easiest tests you will ever write

A reducer is a pure function: (state, action) => newState. No React, no DOM, no mocks. You call it and check the result. If you keep non-trivial state logic in reducers (or other pure functions), most of your logic tests become one-liners.

What should a reducer test cover?

  • Each action type, starting from a realistic state.
  • Edge cases: empty lists, repeating an action, unknown items.
  • Immutability: the old state must be untouched. Freezing the input makes mutation throw an error, so the test fails loudly instead of silently passing.
  • The default branch (an unknown action should fail loudly, or return the state unchanged, whichever your convention is).
Testing a reducer as a plain function

No render, no act: just function calls. These tests run in microseconds, and a table of cases is easy to extend. In Vitest the same idea reads test.each([...])('%s', (name, action, expected) => ...).

A related tip: give your component logic to a reducer or helper function because it is easy to test, not only because it is neat. A calculateTotals(lines, coupon) function with fifteen unit tests is far more reliable than the same logic tangled into JSX.

Testing custom hooks

A hook can only run inside a component. To test one, you render a throwaway probe component that calls the hook and stores what it returns, then you read and drive it from the test. That is all renderHook from Testing Library does. Our version takes the hook, optional initialProps and an optional wrapper (for context providers) and returns { result, rerender }, where result.current always holds the latest return value:

A renderHook helper and a counter hook

Notice three habits:

  • State changes go through act. Calling result.current.increment() outside act triggers the warning you met in the previous lesson. Testing Library's renderHook returns an act function for exactly this.
  • Read result.current after the act, not before. It is replaced on every render. Saving const { count } = result.current early gives you a stale value.
  • The last test documents behavior that surprises people: useState(initial) uses initial only on the first render. A test that records this is cheap insurance when someone "improves" the hook.

The same test with real tools (read-only):

JSX
// read-only: Vitest + @testing-library/react
import { act, renderHook } from '@testing-library/react';
import { expect, test } from 'vitest';
import { useCounter } from './useCounter';

test('increment adds the step each time', () => {
  const { result } = renderHook(() => useCounter({ step: 5 }));

  act(() => result.current.increment());
  act(() => result.current.increment());

  expect(result.current.count).toBe(10);
});

Test a hook directly when it is reusable or has tricky logic. If a hook exists only to serve one component, testing that component usually covers the hook for free and survives refactors better.

Fake timers: debounce without waiting

Logic with setTimeout is slow and flaky to test with real time. A fake clock replaces setTimeout and clearTimeout with versions you control: nothing fires until the test says "advance 300 milliseconds". Then a test of a 300 ms debounce takes a fraction of a millisecond, deterministically.

The hook below returns a value that follows its input only after the input has been still for delay milliseconds. That is the classic search-box debounce. The fake clock is about twenty lines: it records pending timers and runs the due ones in order, inside act, when you call advance.

Testing a debounce hook with a fake clock

The third test checks something users never see but you care about: the effect cleanup cancels the previous timer, so there is never more than one in flight.

Always restore the real timers in a finally block (or in an afterEach). A fake clock left installed breaks every later test in confusing ways. With Vitest the shortcut is:

JavaScript
// read-only: Vitest
import { vi, afterEach } from 'vitest';

afterEach(() => vi.useRealTimers());

test('debounces', () => {
  vi.useFakeTimers();
  // ...render, change input...
  act(() => vi.advanceTimersByTime(300));
});

Mocking fetch

A hook that calls fetch must not hit a real server in tests: it would be slow, flaky and dependent on someone else's uptime. Replace the network with something you control. There are three levels:

  1. Replace globalThis.fetch with a fake (simple, shown below).
  2. Pass the fetcher in as a parameter, or through context (dependency injection). Very easy to test and a fine design.
  3. Intercept at the network layer with MSW (Mock Service Worker). Your code uses the real fetch, and the test says what the "server" answers. This is the most realistic option and survives changes in how requests are made.
Testing a data hook with a fake fetch

Each test needs its own fake and must restore the real fetch afterwards (the finally). Test the unhappy paths as seriously as the happy path: users meet errors more often than you expect. Since the hook above ignores stale responses (ignore), a good extra test would resolve the first request after the second to prove the old answer is discarded; a controllable promise makes that easy.

Testing context and providers

Components and hooks that read context need a provider around them in the test. There are two common approaches:

  • A wrapper option on render and renderHook, which wraps the component in the providers it needs.
  • A renderWithProviders helper in your test utilities that builds the same wrapper with defaults you can override. Every test file then imports one render function instead of repeating the setup.

Context is also a gift to testing: swapping the real service for a fake, or the signed-in user for a test user, is just a matter of what you pass as the provider's value.

Providers, wrappers and a callback spy

The test for WelcomeBanner never signs anyone in. It hands the component a user and a spy and checks the conversation between them. That is the leverage context gives you; compare it with a component that imports a global auth module, which would need module mocking tricks.

Snapshot tests: handle with care

A snapshot test saves the rendered output (usually HTML) the first time, and later compares against it. Any difference fails the test, and a human decides whether the new output is correct and updates the snapshot.

Strengths: a snapshot catches any unintended change, costs one line to write, and suits stable, small, mostly-static output (a formatted invoice string, a generated config file, a serialized error).

Weaknesses, which show up fast on whole component trees:

  • Noise. Changing a class name or adding a wrapper fails dozens of snapshots that are all "still correct".
  • Blind approvals. Reviewers see 400 lines of HTML in a pull request and press "update all". A test that is always updated without reading is not a test.
  • Weak intent. A snapshot does not say what matters. A targeted assertion ("the price shows $12.00") documents the requirement.

The demo compares both styles when a designer changes the markup of a card. The full-HTML snapshot fails; the behavior assertion keeps passing.

Snapshot versus targeted assertion

The V2 snapshot test fails on a change nobody would call a bug. If you use snapshots, keep them small and intentional (one element, one string, one serialized value), keep them inline so reviewers see them, and prefer assertions you can read.

A testing checklist for logic

  • Put rules in pure functions and reducers; test them with plain calls and a table of cases.
  • Test hooks through renderHook, with act around every state change and result.current read after it.
  • Replace time, network and randomness at the edge; restore them in finally or afterEach.
  • Wrap context consumers with providers (a shared renderWithProviders) and supply fakes through them.
  • Test failure paths: rejected promises, HTTP errors, invalid input.
  • Check clean-up (timers cancelled, listeners removed) for hooks that subscribe to things.
  • Keep snapshots rare, small and reviewed.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is a reducer especially easy to test?

    A reducer has no side effects and no dependency on React. Input in, output out.
  2. 2. How can you check that a reducer does not mutate its input?

    Frozen objects reject writes (in strict mode they throw). Immutability bugs become loud failures.
  3. 3. Why do you wrap result.current.increment() in act() when testing a hook?

    act flushes updates and effects so the next read of result.current reflects the new render.
  4. 4. What is the main advantage of fake timers when testing a 300 ms debounce?

    A fake clock fires timers only when the test advances it, so nothing is slow or flaky.
  5. 5. A teammate suggests snapshotting the HTML of every component. What is the most important downside to raise?

    Large snapshots are noisy and weak at expressing intent. Prefer targeted assertions and keep snapshots small.

Summary

  • Keep logic in pure functions and reducers; test them as plain functions, including immutability and the unknown-action case.
  • Test hooks with a probe component (renderHook): wrap changes in act, read result.current afterwards, and use rerender for new props.
  • Control time with fake timers and always restore real timers; control the network with a fake fetch, an injected fetcher or MSW.
  • Test loading, success and error states, and effect cleanup.
  • Provide context in tests with wrappers or a renderWithProviders helper and inject spies or fake services through providers.
  • Use snapshots sparingly: small, inline and reviewed. Prefer explicit assertions about what users should see.

Next: End-to-End and Accessibility Testing