name: react-testing-library description: React Testing Library 模式、查询方法、用户事件和可访问性测试。 allowed-tools: Read, Write, Edit, Bash, Glob, Grep
React Testing Library 技能
用于测试 React 组件的专家级协助。
能力
- 编写以用户为中心的测试
- 使用正确的查询方法
- 处理异步操作
- 测试可访问性
- 模拟依赖项
测试模式
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
describe('登录表单', () => {
it('应使用有效数据提交表单', async () => {
const onSubmit = vi.fn();
const user = userEvent.setup();
render(<LoginForm onSubmit={onSubmit} />);
await user.type(screen.getByLabelText(/邮箱/i), 'test@example.com');
await user.type(screen.getByLabelText(/密码/i), 'password123');
await user.click(screen.getByRole('button', { name: /登录/i }));
await waitFor(() => {
expect(onSubmit).toHaveBeenCalledWith({
email: 'test@example.com',
password: 'password123',
});
});
});
});
查询优先级
- getByRole (可访问性)
- getByLabelText (表单)
- getByPlaceholderText
- getByText
- getByTestId (最后手段)
目标流程
- react测试
- 单元测试
- 可访问性测试