Skip to content

测试 React Hook

测试自定义 Hook in isolation 使用 renderHook and act 到 handle 状态更新.

你将学到

  • 为什么 Hook 需要 host 组件到 是 tested
  • Using renderHook 从 @测试-库/react
  • Wrapping 状态更新 in act 到 flush 副作用
  • 测试副作用, reducers, and 异步 Hook

概念讲解

Hooks Need a Host

A custom hook is just a function that uses React primitives, but the Rules of Hooks require it to run inside a React component. You cannot call useMyHook() directly in a test. renderHook from @测试-库/react provides a hidden host component, runs your hook inside it, and gives you a result.current ref that always points at the latest hook return value.

renderHook

Call const { result, rerender, unmount } = renderHook(() => useMyHook(Props)). Read the current return with result.current. Call rerender with new props to test prop-driven changes, and unmount to test cleanup effects. For hooks that expose callbacks that update state, invoke the callback and then read result.current again — React batches updates, so the ref reflects the post-update value.

The act Warning

React insists that anything which might cause a state update — a callback, an effect, a resolved promise — happens inside act. Testing Library wraps renderHook and userEvent in act automatically, but when you manually await a promise or trigger a timer, you may need 等待 act(异步 () => { ... }). Ignoring act warnings leads to tests that pass but do not reflect real React behavior.

Effects and Async

Effects that fetch data or subscribe to a store are the trickiest. Use waitFor to wait for result.current to reach the expected state after the async work settles. Test cleanup by unmounting and asserting that subscriptions were torn down (often via a spy on the unsubscribe function). Fake timers help when effects debounce or poll.

In Practice

When testing a data-fetching hook, mock the fetch with MSW or a stubbed API client, render the hook, and use waitFor to assert that result.current.数据 eventually equals the expected value and result.current.isLoading becomes false. Test the error path by making the mock reject and asserting the hook surfaces the error. For hooks with cleanup (subscriptions, intervals), call unmount() and verify the teardown ran — a spy on the unsubscribe function makes this concrete. Keep each hook test focused on one piece of behavior (loading state, success, error, cleanup) rather than cramming all paths into one test. If a hook is complex enough that testing it is painful, consider extracting pure logic into a plain function you can unit-test directly, leaving the hook as a thin wrapper.

示例代码

              import { describe, it, expect } from "vitest";
import { renderHook, act } from "@testing-library/react";
import { useCounter } from "./useCounter";

describe("useCounter", () => {
  it("increments and decrements", () => {
    const { result } = renderHook(() => useCounter(0));

    act(() => result.current.increment());
    expect(result.current.count).toBe(1);

    act(() => result.current.decrement());
    expect(result.current.count).toBe(0);
  });

  it("respects an initial value", () => {
    const { result } = renderHook(() => useCounter(10));
    expect(result.current.count).toBe(10);
  });
});
            

renderHook hosts Hook in 隐藏组件. act wraps 每个状态更新所以 React flushes 它之前 assertion 读取 result.current.

动手试一试

  • JSON Formatter

    Inspect 值你的 Hook 返回跨越渲染.

  • Code Diff

    Compare Hook 返回 shapes 当 refactoring internals.

常见错误

错误写法

读取 result.current 不使用 wrapping 更新 in act

正确做法

Wrap 任何回调那个触发状态更新 in act(() => ...). 不使用 act, React warns and assertion 可能读取 stale 值.

错误写法

Calling Hook directly in 测试函数

正确做法

Hook 必须运行内部组件. 总是 use renderHook (or 渲染小 测试组件) — 从不 call useXxx() in bare 测试.

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误