React 组件测试入门
学习使用 React Testing Library 和 Jest 编写可靠的组件测试。 · 难度:入门 · +15XP
为什么要测试 React 组件?
测试可以确保组件在不同输入下行为正确,捕获回归 bug,并让你更有信心重构代码。React Testing Library 鼓励测试用户行为而非实现细节。
1. 环境配置
使用 Create React App 创建的项目已经内置了 Jest 和 Testing Library。你也可以手动安装:npm install @testing-library/react jest。
2. 基本测试结构
import { render, screen } from '@testing-library/react';
import App from './App';
test('renders learn react link', () => {
render(<App />);
const linkElement = screen.getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();
});
3. 常用查询方法
| 方法 | 用途 |
|---|---|
| getByText | 查找文本元素 |
| getByRole | 按 ARIA 角色查找 |
| getByTestId | 按 data-testid 查找 |
4. 模拟用户交互
使用 fireEvent 或 @testing-library/user-event 模拟点击、输入等操作。
练习提示
在下方代码中,点击按钮会显示一条消息。为 App 组件编写一个测试:验证点击按钮后消息是否出现。