测试 React 组件
编写单元 and integration 测试使用 React 测试库 and Jest or Vitest.
你将学到
- philosophy 的 React 测试库
- 渲染组件 and querying DOM
- Firing 事件 and asserting on 输出
- 测试异步 behavior and 用户 interactions
概念讲解
The Testing Philosophy
React Testing Library (RTL) is built on a guiding principle: test your components the way a user would use them. Instead of testing implementation details (component internals, state shape, method calls), you test the rendered output and user interactions. This makes tests more robust to refactoring — if you change the internals but keep the behavior, the tests still pass. RTL renders the component to a real DOM (via jsdom) and provides queries to find elements.
Rendering and Querying
You render a component with 渲染(<MyComponent />) and then query the output. RTL provides several query methods: getByText, getByRole, getByLabelText, getByTestId, and more. The recommended priority is to query by role (accessibility role like "button", "heading", "textbox") because it tests the accessible interface. getBy* throws if not found, queryBy* returns null, and findBy* is async (waits for appearance).
Firing Events
Use userEvent (from @testing-library/user-event) to simulate user interactions. It is more realistic than the lower-level fireEvent — it simulates the full interaction sequence (focus, key presses, blur) and waits for state updates. For example, 等待 用户.点击(button) or 等待 用户.类型(输入, "hello"). Always await userEvent operations because they may trigger async state updates.
Testing Async Behavior
For components that fetch data or show content asynchronously, use findBy* queries which wait for elements to appear (with a timeout). Use waitFor to wait for an assertion to pass. For testing that an element disappears, use waitForElementToBeRemoved. For testing that an element disappears, use waitForElementToBeRemoved. Mock 获取 or API modules with vi.fn() (Vitest) or jest.fn() to control what data is returned and to assert that calls were made with the right arguments.
Test Organization
Organize tests with 描述 blocks that group related tests by component or feature. Use clear 它 names that describe the expected behavior: "displays 错误当 email 是无效" rather than "test1". Aim for tests that are independent — each test should set up its own state and not depend on execution order. Use beforeEach for common setup. Keep tests fast by mocking network calls and avoiding real timers.
示例代码
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, it, expect, vi } from "vitest";
import LoginForm from "./LoginForm";
describe("LoginForm", () => {
it("shows an error for invalid email", async () => {
const user = userEvent.setup();
render(<LoginForm />);
// Query by role — tests the accessible interface.
const emailInput = screen.getByRole("textbox", { name: /email/i });
const submitButton = screen.getByRole("button", { name: /submit/i });
// Simulate user typing and clicking.
await user.type(emailInput, "not-an-email");
await user.click(submitButton);
// Assert the error message appears.
expect(screen.getByText(/valid email required/i)).toBeInTheDocument();
});
it("submits with valid input", async () => {
const onSubmit = vi.fn();
const user = userEvent.setup();
render(<LoginForm onSubmit={onSubmit} />);
await user.type(screen.getByLabelText(/email/i), "[email protected]");
await user.click(screen.getByRole("button", { name: /submit/i }));
expect(onSubmit).toHaveBeenCalledWith({ email: "[email protected]" });
});
});
测试查询通过 role (accessible 接口), use userEvent for realistic interactions, and assert on 可见输出 — 不 implementation details. 这个制作测试 robust 到 refactoring.
动手试一试
- Code Diff
Compare 测试 files 当更新组件 behavior.
- JSON Formatter
格式 mock API 响应数据 used in 你的测试.
常见错误
错误写法
测试 implementation details 相反的 用户 behavior
正确做法
做不 测试组件状态, 内部方法, or 精确渲染数量. 测试什么用户 sees and 做: 查询通过 role, fire 用户事件, assert on 可见输出. 这个制作测试 survive refactoring.
错误写法
Using fireEvent 相反的 userEvent for interactions
正确做法
userEvent simulates 完整 interaction (focus, 输入, blur) and waits for 更新. fireEvent 是 lower-level and 能 miss 状态更新. Prefer userEvent.设置() and 等待用户.点击/类型.
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。