Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 17.6 — Testing Hooks, Context and Reducers
React · Example 2 of 3

Context: a wrapper, a custom render and a hook that needs a provider

Each test says only what is special (signed in or not); the helper supplies the provider. <AuthContext value> is the React 19 way to provide context (Topic 9.2).

Test custom hooks with renderHook and act, give components and hooks the providers they need through a wrapper (usually inside a custom render helper), and test reducers as plain functions with no React at all.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a renderHook test (live helper style) for useToggle(initial) returning [on, toggle]: it starts at the initial value and flips on toggle.

02

Write a custom renderWithTheme(ui, { theme }) helper for a ThemeContext, and a test that a ThemedButton shows class dark in dark mode.

Explain it without notes

01

When do you test a custom hook with renderHook and when through a component?

02

Why must you read result.current after each update, and why wrap hook calls in act?

03

How do you test components that need context, a router or a store?

04

Why are reducers easy to test, and what should reducer tests cover?

Context: a wrapper, a custom render and a hook that needs a provider

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

✓ signed out: shows a log in link
✓ useAuth reads the user from the provider
✓ useAuth outside a provider throws a clear error
✓ signed in: logging out swaps the menu