Token导航 LogoToken导航TokenDH.com
研究检索操作浏览器github未标认证来源可访问许可证需确认审计通过

react-testing-standardsReact 测试 standards

Agent Skill

用于辅助前端页面、组件、样式和交互逻辑的开发与维护。它适合让 Agent 生成或审查 React、Next.js、Vue、Tailwind、CSS 等相关代码,整理组件结构,或定位布局和性能问题。使用时需要结合项目现有设计系统、路由和构建方式,避免只生成孤立片段;涉及页面改动时,应配合本地预览和构建检查确认视觉效果。

总安装

247

周安装

10

GitHub Stars

2

下载量

78
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:react-testing-standards(React 测试 standards)
来源仓库:https://github.com/masanao-ohba/claude-manifests
仓库路径:skills/react-testing-standards
安装命令:
npx skills add https://github.com/masanao-ohba/claude-manifests --skill react-testing-standards
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/masanao-ohba/claude-manifests --skill react-testing-standards

简介

辅助 React 测试标准与规范实施支持。

  • 适用于生成或审查符合团队或行业标准的测试代码。
  • 可整理测试命名、结构组织与文档化策略。react-testing-standards 属于研究检索类 Skill,可作为该场景下的辅助能力补充。
  • 需结合项目测试框架与质量门禁要求使用。
  • 建议在核心模块测试上保持人工审核与持续改进。

SKILL.md

React Testing Standards

Testing Philosophy

Guiding Principles

  • Test user behavior, not implementation details
  • Tests should resemble how users interact with your app
  • Query by accessible roles and labels, not test IDs
  • Integration tests over unit tests when practical
  • Test the component contract, not internal state

What to Test

Priority High:

  • User interactions (clicks, typing, navigation)
  • Conditional rendering based on props/state
  • API integration and data fetching
  • Form submissions and validation
  • Error states and error recovery

Priority Medium:

  • Accessibility features
  • Loading states
  • Edge cases and boundary conditions

Avoid Testing:

  • Implementation details (state variable names)
  • Third-party library internals
  • CSS styling (use visual regression tests)
  • Framework behavior (React itself)

React Testing Library

Query Priority

1. Accessible Queries (Most Preferred):

  • getByRole - Most preferred
  • getByLabelText - For form elements
  • getByPlaceholderText - Alternative for inputs
  • getByText - For non-interactive elements
  • getByDisplayValue - For current input values

2. Semantic Queries:

  • getByAltText - For images
  • getByTitle - For title attributes

3. Test IDs (Last Resort):

  • getByTestId - Only when element has no accessible role

Query Variants

VariantBehavior
getByThrows error if not found - for elements that must exist
queryByReturns null if not found - for asserting non-existence
findByReturns promise - for async elements that appear later

User Interactions

Library: Use @testing-library/user-event, not fireEvent

import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';

test('user can type in input', async () => {
  const user = userEvent.setup();
  render(<SearchBox />);

  const input = screen.getByRole('textbox');
  await user.type(input, 'Hello');

  expect(input).toHaveValue('Hello');
});

Common Interactions:

  • user.click() - Click elements
  • user.type() - Type in inputs
  • user.clear() - Clear input values
  • user.selectOptions() - Select dropdown options
  • user.upload() - Upload files

Test Structure

Anatomy

import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { ComponentName } from './ComponentName';

describe('ComponentName', () => {
  test('describes expected behavior', async () => {
    // Arrange - Set up test data and render
    const user = userEvent.setup();
    render(<ComponentName prop="value" />);

    // Act - Perform user interactions
    const button = screen.getByRole('button', { name: /click me/i });
    await user.click(button);

    // Assert - Verify expected outcomes
    expect(screen.getByText(/success/i)).toBeInTheDocument();
  });
});

Best Practices

  • One logical assertion per test
  • Descriptive test names (what behavior is tested)
  • Arrange-Act-Assert pattern
  • Avoid beforeEach for test setup (makes tests less clear)
  • Use async/await for user interactions

Testing Patterns

Component Rendering

Basic:

test('renders with correct props', () => {
  render(<UserCard name="John" email="john@example.com" />);

  expect(screen.getByText('John')).toBeInTheDocument();
  expect(screen.getByText('john@example.com')).toBeInTheDocument();
});

Conditional:

test('shows loading state', () => {
  render(<DataDisplay isLoading={true} />);

  expect(screen.getByRole('progressbar')).toBeInTheDocument();
});

User Interactions

Button Click:

test('increments counter on click', async () => {
  const user = userEvent.setup();
  render(<Counter />);

  const button = screen.getByRole('button', { name: /increment/i });
  await user.click(button);

  expect(screen.getByText('Count: 1')).toBeInTheDocument();
});

Form Submission:

test('submits form with user data', async () => {
  const handleSubmit = jest.fn();
  const user = userEvent.setup();
  render(<LoginForm onSubmit={handleSubmit} />);

  await user.type(screen.getByLabelText(/email/i), 'user@example.com');
  await user.type(screen.getByLabelText(/password/i), 'password123');
  await user.click(screen.getByRole('button', { name: /submit/i }));

  expect(handleSubmit).toHaveBeenCalledWith({
    email: 'user@example.com',
    password: 'password123',
  });
});

Async Operations

Data Fetching:

test('displays fetched data', async () => {
  render(<UserList />);

  // Wait for loading to finish
  expect(screen.getByText(/loading/i)).toBeInTheDocument();

  // Wait for data to appear
  const users = await screen.findAllByRole('listitem');
  expect(users).toHaveLength(3);
});

With waitFor:

test('shows success message after submission', async () => {
  const user = userEvent.setup();
  render(<ContactForm />);

  await user.click(screen.getByRole('button', { name: /submit/i }));

  await waitFor(() => {
    expect(screen.getByText(/thank you/i)).toBeInTheDocument();
  });
});

Error Handling

test('displays error message on failure', async () => {
  // Mock API to return error
  jest.spyOn(api, 'fetchUser').mockRejectedValue(new Error('Failed'));

  render(<UserProfile userId="123" />);

  const errorMessage = await screen.findByText(/failed to load/i);
  expect(errorMessage).toBeInTheDocument();
});

Mocking

External Dependencies

API Calls:

// Mock API module
jest.mock('@/lib/api', () => ({
  fetchUsers: jest.fn(),
}));

test('renders users from API', async () => {
  const mockUsers = [{ id: 1, name: 'Alice' }];
  fetchUsers.mockResolvedValue(mockUsers);

  render(<UserList />);

  expect(await screen.findByText('Alice')).toBeInTheDocument();
});

React Query:

import { QueryClient, QueryClientProvider } from '@tanstack/react-query';

function renderWithQueryClient(ui: React.ReactElement) {
  const queryClient = new QueryClient({
    defaultOptions: {
      queries: { retry: false },
    },
  });

  return render(
    <QueryClientProvider client={queryClient}>
      {ui}
    </QueryClientProvider>
  );
}

What NOT to Mock

Avoid:

  • React hooks (useState, useEffect, etc.)
  • Component implementation details
  • Child components (test integration instead)

Acceptable:

  • External API calls
  • Browser APIs (localStorage, fetch)
  • Third-party libraries with side effects
  • Date/time functions (Date.now())

Accessibility Testing

Practices

  • Query by role (getByRole) enforces ARIA compliance
  • Test keyboard navigation
  • Verify focus management
  • Check alt text on images
test('button is keyboard accessible', async () => {
  const user = userEvent.setup();
  render(<Dialog />);

  // Tab to button
  await user.tab();
  expect(screen.getByRole('button')).toHaveFocus();

  // Activate with Enter
  await user.keyboard('{Enter}');
  expect(screen.getByRole('dialog')).toBeInTheDocument();
});

Test Organization

File Structure

  • ComponentName.test.tsx - Component tests
  • utils.test.ts - Utility function tests
  • __tests__/ directory - Alternative structure

Describe Blocks

describe('LoginForm', () => {
  describe('validation', () => {
    test('shows error for invalid email', () => {});
    test('shows error for short password', () => {});
  });

  describe('submission', () => {
    test('calls onSubmit with form data', () => {});
    test('shows success message after submit', () => {});
  });
});

Coverage Guidelines

Requirements

AreaCoverage
Critical paths100%
Components80%+
Utilities90%+

What to Prioritize

  • User-facing features
  • Business logic and calculations
  • Error handling paths
  • Form validation

Acceptable Gaps

  • Pure presentation components
  • Third-party library wrappers
  • Type definitions

Common Pitfalls

Avoid

  • Testing implementation details (state names, effect calls)
  • Snapshot tests for everything (brittle and uninformative)
  • Using getByTestId as primary query method
  • Not awaiting async operations
  • Asserting on intermediate loading states

Instead

  • Test public API and user-visible behavior
  • Snapshots only for static content that changes infrequently
  • Query by role/label for accessibility
  • Always await user events and async queries
  • Assert on final rendered state

CI Integration

Requirements

  • All tests must pass before merge
  • Coverage reports generated and tracked
  • Tests run on every pull request
  • Fast test execution (< 5 minutes for unit/integration)

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

35.9%
按下载量换算28

Claude

28.87%
按下载量换算23

Cursor

18.27%
按下载量换算14

Gemini CLI

8.01%
按下载量换算6

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

操作浏览器

该 Skill 可能涉及浏览器控制能力,使用时可能读取或操作网页内容,需要在受控环境中确认权限边界。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills