Repolode
testing-library

testing-library/react-testing-library

轻量的 React DOM 测试工具,按用户实际使用的方式查询和操作组件。

Star
19,672
Fork
1,171
未关闭 Issue
84
最近提交
2个月前

这是什么?

React Testing Library 基于 react-dom 和 react-dom/test-utils 提供测试 React 组件的工具函数。它的核心理念是测试应尽量贴近软件的真实使用方式,因此围绕 DOM 节点而非组件实例设计,避免依赖组件内部实现细节。

库中提供 render、screen 查询(如 getByRole、getByLabelText、getByText),以及用于模拟用户操作的 fireEvent。get、query、find 等前缀分别对应断言元素存在、断言元素不存在和等待元素出现等常见场景。16 版本起需要额外安装 @testing-library/dom,13 及以上版本要求 React 18。

它通常与 Jest 等测试框架搭配使用,并可结合 @testing-library/jest-dom 进行 DOM 断言,或用 Mock Service Worker 模拟接口请求。若要测试可复用的自定义 Hook,可以使用单独的 React Hooks Testing Library。

核心功能

  • 01通过可访问的角色、标签和文本查询元素,与用户的查找方式一致。
  • 02提供 render 和 fireEvent 等工具,用于挂载组件和模拟交互。
  • 03包含 find、waitFor 等异步工具,便于测试异步界面更新。
  • 04基于 react-dom 构建,可与 Jest 等测试运行器配合使用。
  • 05可搭配 jest-dom 匹配器编写可读性更好的 DOM 断言。

适用场景

  • 为 React 组件编写单元或集成测试,使测试在重构后依然稳定。
  • 测试 React 应用中的表单、用户操作流程和条件渲染。
  • 验证加载状态、数据获取完成后等异步界面行为。

快速上手

  1. 1

    使用 npm 将 React Testing Library 和 DOM 测试工具安装为开发依赖

    npm install --save-dev @testing-library/react @testing-library/dom
  2. 2

    或者改用 yarn 安装

    yarn add --dev @testing-library/react @testing-library/dom
  3. 3

    编写测试:使用库提供的 render 和 screen 渲染组件,并像用户一样进行查询

使用前须知

  • 从第 16 版起需要单独安装 @testing-library/dom。
  • 第 13 版及以上需要 React 18;较旧的 React 项目必须使用第 12 版。

标签

常见问题

react-testing-library 是什么?
轻量的 React DOM 测试工具,按用户实际使用的方式查询和操作组件。 React Testing Library 基于 react-dom 和 react-dom/test-utils 提供测试 React 组件的工具函数。它的核心理念是测试应尽量贴近软件的真实使用方式,因此围绕 DOM 节点而非组件实例设计,避免依赖组件内部实现细节。
react-testing-library 可以免费使用吗?用的什么许可证?
react-testing-library 以 MIT 许可证开源。用于商业产品前,请先确认许可证条款。
react-testing-library 还在维护吗?
半年内有更新。react-testing-library 最近一次提交是在 2026年8月27日。
react-testing-library 适合用来做什么?
为 React 组件编写单元或集成测试,使测试在重构后依然稳定。 测试 React 应用中的表单、用户操作流程和条件渲染。 验证加载状态、数据获取完成后等异步界面行为。
react-testing-library 怎么安装和运行?
使用 npm 将 React Testing Library 和 DOM 测试工具安装为开发依赖: npm install --save-dev @testing-library/react @testing-library/dom 或者改用 yarn 安装: yarn add --dev @testing-library/react @testing-library/dom 编写测试:使用库提供的 render 和 screen 渲染组件,并像用户一样进行查询
在哪里获取 react-testing-library?
源代码和安装说明在 GitHub 上:https://github.com/testing-library/react-testing-library

概要由 AI 根据项目 README 生成;GitHub 数据每日更新。

相关项目