测试 React 组件
渲染, 查询, and assert on 组件使用测试库 and Vitest.
你将学到
- 渲染组件到 jsdom 环境使用渲染
- Querying 通过 role and 文本相反的 implementation details
- Firing 用户事件 and awaiting 异步 UI 更新
- Asserting accessibility and 可见 behavior, 不 internals
概念讲解
Testing Library Philosophy
React Testing Library (with @testing-library/react and @testing-library/user-event) renders your component into a fake DOM and lets you query and interact with it the way a real user would — by visible text, roles, and labels. Its guiding principle is "the more your tests resemble the way your software is used, the more confidence they give you." It deliberately avoids exposing component internals, steering you toward testing behavior.
Setup
Configure Vitest with 环境: 'jsdom' (or 'happy-dom') so document exists. Install @测试-库/react, @测试-库/jest-DOM (for matchers like toBeInTheDocument), and @测试-库/用户-事件 for realistic events. Add setupFiles that imports @测试-库/jest-DOM/vitest to register the matchers.
Queries and Events
Prefer getByRole and getByLabelText over getByTestId — role-based queries also enforce accessibility (a button with no accessible name fails the query). Use userEvent.点击 and userEvent.类型 rather than fireEvent, because userEvent simulates the full user interaction sequence (focus, key presses, change events). For async UI, findBy queries wait for elements to appear, and waitFor wraps assertions that settle after a tick.
What to Assert
Assert on what the user sees: visible text, presence of an error message, that a link points to the right URL. Avoid asserting on internal state, component instance methods, or CSS class names that are implementation details. When a component's behavior changes but its visible output does not, your tests should not need to change.
In Practice
A healthy component test suite renders each component in a few representative states (default, loading, error, empty) and asserts on the visible output and the user interactions. Mock the data-fetching layer at the boundary so tests stay fast and do not hit the network, but let the component's own rendering and event handling run for real. Use findBy queries for elements that appear after an async update, and waitFor to assert on state that settles after a tick. Avoid snapshot tests for components unless the output is stable and someone will review the diffs — behavior assertions are more meaningful. When a test breaks because you renamed a CSS class, the test was too coupled to implementation; rewrite it to query by role or visible text so it survives styling refactors.
示例代码
import { describe, it, expect } from "vitest";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { Counter } from "./Counter";
describe("Counter", () => {
it("increments when the button is clicked", async () => {
const user = userEvent.setup();
render(<Counter />);
const button = screen.getByRole("button", { name: /increment/i });
expect(screen.getByText("Count: 0")).toBeInTheDocument();
await user.click(button);
expect(screen.getByText("Count: 1")).toBeInTheDocument();
});
});
测试渲染计数器, 查找 button 通过它的 accessible name, 点击它 通过 userEvent, and asserts 可见文本更新. 否 internals 是 touched.
动手试一试
- JSON Formatter
Inspect Props and 状态你 通过到 组件.
- Code Diff
Compare rendered 输出 snapshots 当组件更改.
常见错误
错误写法
Querying 通过 CSS 类 or testid 相反的 role
正确做法
Prefer getByRole and getByLabelText. 它们测试 accessibility 也 — 组件那个是 不 queryable 通过 role 是不 usable 通过 screen readers.
错误写法
Using fireEvent 相反的 userEvent for interactions
正确做法
userEvent simulates 真实用户序列 (focus, keydown, 输入, keyup). fireEvent dispatches 单个 synthetic 事件 and misses 真实-世界边 副作用.
练习 测试 React 组件
6 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。