以下是关于 React Testing Library(RTL)的深度知识体系总结:
一、核心设计哲学
1. 核心理念
"测试应尽可能接近用户真实使用方式"
- 用户视角优先:只测试用户能感知的交互和输出
- 实现不可知:不测试组件内部状态/方法(黑盒测试)
- 无障碍友好:通过语义化查询促进可访问性开发
2. 与 Enzyme 对比
维度 | React Testing Library | Enzyme |
---|
测试重点 | 行为结果 | 实现细节 |
查询方式 | DOM 语义查询 | 组件实例操作 |
推荐场景 | 用户行为验收测试 | 组件内部逻辑测试 |
二、基础使用
1. 安装与配置
npm install @testing-library/react @testing-library/jest-dom @testing-library/user-event
module.exports = {setupFilesAfterEnv: ['@testing-library/jest-dom/extend-expect']
}
2. 核心 API 三要素
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';test('基础测试流程', () => {render(<LoginForm />);const input = screen.getByLabelText(/username/i);userEvent.type(input, 'testuser');expect(input).toHaveValue('testuser');
});
三、查询策略体系
1. 查询方法矩阵
方法类型 | 示例 | 失败行为 | 适用场景 |
---|
getBy | getByRole('button') | 立即报错 | 元素必须存在 |
queryBy | queryByText('Submit') | 返回 null | 断言元素不存在 |
findBy | findByText('Loading...') | 异步等待 | 等待元素出现 |
getAllBy | getAllByRole('listitem') | 立即报错 | 多个元素存在 |
2. 查询优先级准则
1. 可访问性查询:getByRole > getByLabelText > getByPlaceholderText
2. 语义化查询:getByAltText > getByTitle
3. 最后选择:getByTestId(需添加 data-testid)
3. 最佳查询实践
// 推荐:通过角色和名称定位
<button aria-label="delete">×</button>
const button = screen.getByRole('button', { name: /delete/i });// 避免:使用实现细节查询
screen.getByTestId('submit-button'); // 除非必要
四、异步操作处理