React测试库Skill react-testing-library

React 测试库技能提供专业的 React 组件测试解决方案,专注于编写以用户为中心的测试用例、使用最佳查询方法、处理异步操作、确保组件可访问性以及模拟外部依赖。适用于前端开发中的单元测试、集成测试和可访问性测试,是提升 React 应用质量和用户体验的关键工具。关键词:React 测试,前端测试,单元测试,可访问性测试,测试库,用户事件模拟。

测试 0 次安装 1 次浏览 更新于 2/26/2026

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',
      });
    });
  });
});

查询优先级

  1. getByRole (可访问性)
  2. getByLabelText (表单)
  3. getByPlaceholderText
  4. getByText
  5. getByTestId (最后手段)

目标流程

  • react测试
  • 单元测试
  • 可访问性测试