react-testing-library

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

React Testing Library Best Practices

React Testing Library 最佳实践

Comprehensive testing guide for React components using Testing Library, designed for AI agents and LLMs. Contains 43 rules across 9 categories, prioritized by impact to guide test writing and code review.
这是一份针对使用Testing Library测试React组件的综合指南,专为AI Agent和LLM设计。包含9个类别共43条规则,按影响优先级排序,用于指导测试编写和代码评审。

When to Apply

适用场景

Reference these guidelines when:
  • Writing new component tests with React Testing Library
  • Selecting queries (getByRole, getByLabelText, etc.)
  • Handling async operations in tests (findBy, waitFor)
  • Simulating user interactions (userEvent)
  • Reviewing tests for anti-patterns and implementation detail testing
在以下场景中参考这些指南:
  • 使用React Testing Library编写新的组件测试时
  • 选择查询方法(getByRole、getByLabelText等)时
  • 处理测试中的异步操作(findBy、waitFor)时
  • 模拟用户交互(userEvent)时
  • 评审测试以发现反模式和对实现细节的测试时

Rule Categories by Priority

按优先级划分的规则类别

PriorityCategoryImpactPrefix
1Query SelectionCRITICAL
query-
2Async HandlingCRITICAL
async-
3Common Anti-PatternsCRITICAL
anti-
4User InteractionHIGH
user-
5AssertionsHIGH
assert-
6Component SetupMEDIUM
setup-
7Test StructureMEDIUM
struct-
8DebuggingLOW-MEDIUM
debug-
9Accessibility TestingLOW
a11y-
优先级类别影响程度前缀
1查询选择关键
query-
2异步处理关键
async-
3常见反模式关键
anti-
4用户交互
user-
5断言
assert-
6组件设置
setup-
7测试结构
struct-
8调试低-中
debug-
9可访问性测试
a11y-

Quick Reference

快速参考

1. Query Selection (CRITICAL)

1. 查询选择(关键)

  • query-prefer-role
    - Prefer getByRole over other queries
  • query-avoid-testid
    - Avoid getByTestId as primary query
  • query-use-screen
    - Use screen for queries
  • query-label-text-forms
    - Use getByLabelText for form fields
  • query-role-name-option
    - Use name option with getByRole
  • query-get-vs-query
    - Use getBy for present, queryBy for absent
  • query-within-scope
    - Use within() to scope queries
  • query-prefer-role
    - 优先使用getByRole而非其他查询方法
  • query-avoid-testid
    - 避免将getByTestId作为主要查询方法
  • query-use-screen
    - 使用screen进行查询
  • query-label-text-forms
    - 对表单字段使用getByLabelText
  • query-role-name-option
    - 结合name选项使用getByRole
  • query-get-vs-query
    - 存在元素时用getBy,不存在时用queryBy
  • query-within-scope
    - 使用within()限定查询范围

2. Async Handling (CRITICAL)

2. 异步处理(关键)

  • async-findby-over-waitfor
    - Use findBy instead of waitFor + getBy
  • async-await-findby
    - Always await findBy queries
  • async-single-assertion-waitfor
    - Single assertion in waitFor
  • async-no-side-effects-waitfor
    - Avoid side effects in waitFor
  • async-waitfor-disappear
    - Use waitForElementToBeRemoved
  • async-findby-over-waitfor
    - 使用findBy而非waitFor + getBy
  • async-await-findby
    - 始终对findBy查询使用await
  • async-single-assertion-waitfor
    - 在waitFor中仅包含单个断言
  • async-no-side-effects-waitfor
    - 避免在waitFor中产生副作用
  • async-waitfor-disappear
    - 使用waitForElementToBeRemoved

3. Common Anti-Patterns (CRITICAL)

3. 常见反模式(关键)

  • anti-unnecessary-act
    - Avoid unnecessary act() wrapping
  • anti-manual-cleanup
    - Remove manual cleanup calls
  • anti-implementation-details
    - Avoid testing implementation details
  • anti-empty-waitfor
    - Avoid empty waitFor callbacks
  • anti-container-queries
    - Avoid using container for queries
  • anti-redundant-roles
    - Avoid adding redundant ARIA roles
  • anti-unnecessary-act
    - 避免不必要的act()包裹
  • anti-manual-cleanup
    - 移除手动清理调用
  • anti-implementation-details
    - 避免测试实现细节
  • anti-empty-waitfor
    - 避免空的waitFor回调
  • anti-container-queries
    - 避免使用container进行查询
  • anti-redundant-roles
    - 避免添加冗余的ARIA角色

4. User Interaction (HIGH)

4. 用户交互(高)

  • user-prefer-userevent
    - Use userEvent over fireEvent
  • user-setup-before-render
    - Setup userEvent before render
  • user-await-interactions
    - Always await userEvent interactions
  • user-keyboard-for-special-keys
    - Use keyboard() for special keys
  • user-clear-before-type
    - Use clear() before retyping
  • user-prefer-userevent
    - 使用userEvent而非fireEvent
  • user-setup-before-render
    - 在渲染前设置userEvent
  • user-await-interactions
    - 始终对userEvent交互使用await
  • user-keyboard-for-special-keys
    - 对特殊按键使用keyboard()
  • user-clear-before-type
    - 重新输入前使用clear()

5. Assertions (HIGH)

5. 断言(高)

  • assert-jest-dom-matchers
    - Use jest-dom matchers
  • assert-visible-over-in-document
    - Use toBeVisible() for visibility
  • assert-text-content
    - Use toHaveTextContent() for text
  • assert-have-value
    - Use toHaveValue() for inputs
  • assert-accessible-description
    - Use toHaveAccessibleDescription()
  • assert-jest-dom-matchers
    - 使用jest-dom匹配器
  • assert-visible-over-in-document
    - 使用toBeVisible()判断可见性
  • assert-text-content
    - 使用toHaveTextContent()判断文本
  • assert-have-value
    - 使用toHaveValue()判断输入框值
  • assert-accessible-description
    - 使用toHaveAccessibleDescription()

6. Component Setup (MEDIUM)

6. 组件设置(中)

  • setup-wrapper-providers
    - Use wrapper option for providers
  • setup-custom-render
    - Create custom render with providers
  • setup-mock-modules
    - Mock modules at module level
  • setup-fake-timers
    - Configure userEvent with fake timers
  • setup-render-hook
    - Use renderHook for testing hooks
  • setup-wrapper-providers
    - 使用wrapper选项配置提供者
  • setup-custom-render
    - 创建带有提供者的自定义render
  • setup-mock-modules
    - 在模块级别模拟模块
  • setup-fake-timers
    - 结合fake timers配置userEvent
  • setup-render-hook
    - 使用renderHook测试钩子

7. Test Structure (MEDIUM)

7. 测试结构(中)

  • struct-arrange-act-assert
    - Follow Arrange-Act-Assert pattern
  • struct-one-behavior-per-test
    - Test one behavior per test
  • struct-descriptive-names
    - Use descriptive test names
  • struct-avoid-beforeeach-render
    - Avoid render() in beforeEach
  • struct-arrange-act-assert
    - 遵循Arrange-Act-Assert模式
  • struct-one-behavior-per-test
    - 每个测试仅验证一个行为
  • struct-descriptive-names
    - 使用描述性的测试名称
  • struct-avoid-beforeeach-render
    - 避免在beforeEach中调用render()

8. Debugging (LOW-MEDIUM)

8. 调试(低-中)

  • debug-screen-debug
    - Use screen.debug() to inspect DOM
  • debug-logroles
    - Use logRoles to find available roles
  • debug-testing-playground
    - Use Testing Playground for queries
  • debug-screen-debug
    - 使用screen.debug()检查DOM
  • debug-logroles
    - 使用logRoles查找可用角色
  • debug-testing-playground
    - 使用Testing Playground编写查询

9. Accessibility Testing (LOW)

9. 可访问性测试(低)

  • a11y-role-queries-verify
    - Role queries verify accessibility
  • a11y-verify-focus
    - Test focus management
  • a11y-test-aria-states
    - Test ARIA states and properties
  • a11y-role-queries-verify
    - 通过角色查询验证可访问性
  • a11y-verify-focus
    - 测试焦点管理
  • a11y-test-aria-states
    - 测试ARIA状态和属性

How to Use

使用方法

Read individual reference files for detailed explanations and code examples:
  • Section definitions - Category structure and impact levels
  • Rule template - Template for adding new rules
阅读各个参考文件以获取详细说明和代码示例:
  • 章节定义 - 类别结构和影响级别
  • 规则模板 - 添加新规则的模板

Reference Files

参考文件

FileDescription
references/_sections.mdCategory definitions and ordering
assets/templates/_template.mdTemplate for new rules
metadata.jsonVersion and reference information
文件描述
references/_sections.md类别定义和排序
assets/templates/_template.md新规则模板
metadata.json版本和参考信息