# 测试库

**测试库**（Testing Library）是一系列 [JavaScript](https://www.edgepedia.org/zh/javascript) 测试工具，以与框架无关的 DOM 测试库为首，帮助开发者像用户一样测试 Web 用户界面——通过文本、标签、角色以及其他可见或可访问的属性来查找元素，而不是通过实现细节。它由肯特·C·多兹（Kent C. Dodds）创建，他于 2018 年 4 月 2 日推出了最初的 React 包 react-testing-library，如今它已为 React、Vue、Angular、Svelte 等框架提供封装，也为 Cypress 和 WebdriverIO 等端到端工具提供支持。<sup>[1](https://kentcdodds.com/blog/introducing-the-react-testing-library)</sup><sup> • </sup><sup>[2](https://testing-library.com/docs/react-testing-library/api/)</sup>

| 关键事实 | 详情 |
|---|---|
| 创建者 | 肯特·C·多兹；react-testing-library 于 2018 年 4 月 2 日发布<sup>[1](https://kentcdodds.com/blog/introducing-the-react-testing-library)</sup> |
| 核心原则 | “测试越接近软件的使用方式，能给你的信心就越多”；工具处理的是 DOM 节点，而非组件实例<sup>[3](https://testing-library.com/docs/guiding-principles/)</sup> |
| 查询家族 | `getBy` 在零个或多个匹配时抛出错误，`queryBy` 在无匹配时返回 `null`，`findBy` 返回一个 Promise 并以 1000 毫秒的默认超时重试<sup>[4](https://testing-library.com/docs/queries/about/)</sup> |
| 最推荐的查询 | `getByRole` 查询可访问性树，并可按可访问名称过滤，是大多数元素的首选<sup>[4](https://testing-library.com/docs/queries/about/)</sup> |
| `screen` 导出 | 每个查询都预先绑定到 `document.body`，因此测试无需传入容器参数<sup>[4](https://testing-library.com/docs/queries/about/)</sup> |
| 当前 React 版本 | v16.3.3（2026-08-27）；v16.0.0（2024-06-03）将 `@testing-library/dom` 设为对等依赖，v16.1.0（2024-12-05）新增对 React 19 的支持<sup>[5](https://github.com/testing-library/react-testing-library/releases)</sup> |
| 采用情况 | 截至 2026 年 3 月，`@testing-library/react` 每周 npm 下载量约 1500 万次，而 Enzyme 约为 300 万次<sup>[6](https://www.pkgpulse.com/guides/testing-library-vs-enzyme-2026)</sup> |

## 指导原则

该项目为其包含哪些工具陈述了三项原则：与渲染相关的工具应处理 DOM 节点而非组件实例；工具应普遍适用于按照用户使用组件的方式来测试组件；实现和 API 应简单而灵活。<sup>[3](https://testing-library.com/docs/guiding-principles/)</sup> 文档直接阐述了可访问性方面的动机：API 应让你能像用户使用应用那样测试应用，包括通过屏幕阅读器等可访问性接口。<sup>[7](https://testing-library.com/docs/dom-testing-library/api-accessibility/)</sup>

这一理念是与 Enzyme 的主要区别所在，后者是爱彼迎早期推出的 React 测试工具。Enzyme 暴露组件内部结构，如实例状态和 props，而测试库将组件渲染到 DOM，并对该 DOM 树进行断言。<sup>[8](https://library.knu.edu.af/opac/temp/14281.pdf)</sup> 测试库的迁移指南引用了多兹关于测试内部结构代价的论述：使用 `instance()` 或 `state()` 的测试所测的是用户无法知道或关心的事情，这使测试偏离了“用户使用时一切正常”的信心。<sup>[9](https://testing-library.com/docs/react-testing-library/migrate-from-enzyme/)</sup>

## 查询

查询是测试库提供的用于在页面上查找元素的方法。每个查询都有三种变体，区别在于失败行为：`getBy` 返回匹配的节点，若无元素匹配或有多个匹配则抛出描述性错误；`queryBy` 在无匹配时返回 `null`，适合断言某元素不存在；`findBy` 返回一个 Promise，在元素出现时兑现，超过默认的 1000 毫秒超时时限后拒绝。复数形式（`getAllBy`、`queryAllBy`、`findAllBy`）则返回数组。<sup>[4](https://testing-library.com/docs/queries/about/)</sup>

`findBy` 方法将 `getBy` 查询与 `waitFor` 异步工具结合，并接受 `waitFor` 选项作为最后一个参数，因此适合仅在事件发生、超时或 Promise 兑现之后才出现的元素。<sup>[4](https://testing-library.com/docs/queries/about/)</sup><sup> • </sup><sup>[10](https://testing-library.com/docs/dom-testing-library/api-async/)</sup>

**查询优先级。** 文档推荐了一个基于用户查找元素方式的顺序。所有人都能访问的查询排在前面：`getByRole`（可查询可访问性树中暴露的任何元素，并按可访问名称过滤，如 `getByRole('button', {name: /submit/i})`），然后是用于表单字段的 `getByLabelText`、`getByPlaceholderText`、`getByText` 和 `getByDisplayValue`。语义化 HTML5 和 ARIA 选择器，如 `getByAltText` 和 `getByTitle`，排在第二位，但需注意屏幕阅读器对 `title` 属性的读取并不一致。`getByTestId` 排在最后，仅在角色或文本匹配不合理时（例如文本是动态的）才推荐使用。<sup>[4](https://testing-library.com/docs/queries/about/)</sup>

**匹配与规范化。** 大多数查询接受一个 `TextMatch` 参数：字符串、正则表达式，或形如 `(content, element) => boolean` 的函数。字符串匹配默认 `exact: true`，即全字符串、区分大小写的匹配；设置 `exact: false` 则启用子串、不区分大小写的匹配。匹配之前，库会对文本进行规范化：去除字符串两端的空白，并将相邻的空白字符合并为一个空格；自定义的 `normalizer` 函数可以替换或扩展此行为。<sup>[4](https://testing-library.com/docs/queries/about/)</sup>

**使用查询。** 基础 DOM 测试库的查询以 `container` 作为第一个参数，但框架封装在你渲染组件时会预先绑定查询，而 `screen` 导出将每个查询预先绑定到 `document.body`，这是文档推荐的做法。一个典型的 React 测试会渲染组件，然后用 `screen.getByLabelText('Username')` 查找输入框。<sup>[4](https://testing-library.com/docs/queries/about/)</sup> 要将查询限定在页面的一部分，`within` 辅助函数可将匹配限制在特定元素的子元素内。<sup>[4](https://testing-library.com/docs/queries/about/)</sup>

## 交互与断言

选定元素后，测试会模拟用户交互并对结果进行断言。事件 API 的 `fireEvent` 在给定元素上调用 `dispatchEvent`，而独立的 `user-event` 包构建在 `fireEvent` 之上，通常更受推荐，因为它会按典型用户交互的正确顺序触发事件。<sup>[9](https://testing-library.com/docs/react-testing-library/migrate-from-enzyme/)</sup> 对于断言，文档将测试库与 Jest 和 jest-dom 搭配使用，后者是一组针对 DOM 状态的自定义匹配器。<sup>[4](https://testing-library.com/docs/queries/about/)</sup><sup> • </sup><sup>[11](https://sitelet.easiiodev.ai/sitelet?url=https%3A%2F%2Fgithub.com%2Ftesting-library)</sup>

## 框架封装与生态

DOM 测试库是核心；各框架包重新导出其查询并添加 `render` 方法。React 测试库重新导出 DOM 测试库的所有内容，并添加带 `container`、`baseElement`、`hydrate` 和 `legacyRoot` 等选项的 `render`；它返回的查询绑定到 `baseElement`，后者默认为 `document.body`。<sup>[2](https://testing-library.com/docs/react-testing-library/api/)</sup> 文档中列出的封装包括 React、Vue、Angular、Svelte、Marko、Preact、Reason、Native、Solid 和 Qwik，以及与浏览器驱动工具的集成：Cypress、Puppeteer、Testcafe、Nightwatch 和 WebdriverIO。<sup>[2](https://testing-library.com/docs/react-testing-library/api/)</sup> Cypress 集成允许在 Cypress 端到端测试中使用 DOM 查询，<sup>[12](https://testing-library.com/docs/cypress-testing-library/intro/)</sup> 而 Puppeteer 集成在每次查询时都将 DOM 测试库注入受控页面，因此其所有结果都是异步的。<sup>[13](https://testing-library.com/docs/pptr-testing-library/intro/)</sup>

采用建议因框架而异。官方 Vue 测试指南推荐在应用中使用 `@vue/test-utils` 进行组件测试，并警告 `@testing-library/vue` 在测试带 Suspense 的异步组件时存在问题，应谨慎使用。<sup>[14](https://vuejs.org/guide/scaling-up/testing)</sup> 自定义查询也受支持：DOM 测试库暴露其默认查询所使用的辅助函数，自定义查询可通过 `queries` 选项添加到 React 测试库的 `render` 中。<sup>[15](https://testing-library.com/docs/dom-testing-library/api-custom-queries/)</sup>

## 可访问性辅助工具

由于查询优先级围绕可访问性树构建，DOM 测试库包含了检查它的辅助工具。`getRoles` 遍历 DOM 树中的隐式 ARIA 角色，返回一个以角色名称为索引的对象，每个值是一个匹配元素的数组。`logRoles` 打印相同的信息，有助于找到用 `getByRole` 查询 DOM 的方法。`isInaccessible` 计算浏览器是否应将某元素从可访问性 API 中排除，实现了 WAI-ARIA 1.2 中关于从可访问性树排除元素一节的每一条必须遵守的标准，但检查 `role` 属性除外。<sup>[7](https://testing-library.com/docs/dom-testing-library/api-accessibility/)</sup>

## 历史与维护

该项目最初是 react-testing-library，由肯特·C·多兹于 2018 年 4 月发布，定位为“简单而完整的 React DOM 测试工具，鼓励良好的测试实践”，并暴露了一个 `data-testid` 查询，作为无法合理地通过文本和标签查找元素时的备用手段。<sup>[1](https://kentcdodds.com/blog/introducing-the-react-testing-library)</sup> 后来它迁移到带作用域的 `@testing-library/react` 包名和组织所有的 testing-library GitHub 仓库。<sup>[16](https://support.bigfix.com/product/documents/opensource/Notices_BigFix_Remediate_V11_July2024.pdf)</sup>

近期的发布显示出稳定、渐进的维护。16.0.0 版（2024 年 6 月）将 `@testing-library/dom` 和 `@types/react-dom` 移至对等依赖，这一破坏性变更旨在减少 DOM 包版本冲突——该冲突曾导致 `@testing-library/user-event` 的缺陷。16.1.0 版（2024 年 12 月）新增对 React 19 的支持，随后至 2026 年 8 月的 16.2.x 和 16.3.x 版本修复了诸如派发事件时 `act()` 重入以及 React 19 下 `onCaughtError` 类型推断等问题。<sup>[5](https://github.com/testing-library/react-testing-library/releases)</sup>

## 与 Enzyme 的比较

Enzyme 由爱彼迎开发，多年来是最流行的 React 测试库，提供浅渲染以及对组件状态和 props 的访问。<sup>[8](https://library.knu.edu.af/opac/temp/14281.pdf)</sup> 截至 2026 年 3 月，`@testing-library/react` 每周下载量约 1500 万次，而 Enzyme 约 300 万次；Enzyme 从未获得官方的 React 18 适配器，也不支持 React 19。实用建议是：在 React 18 及更高版本上使用测试库，而将 Enzyme 保留给遗留的 React 16 或 17 代码库。<sup>[6](https://www.pkgpulse.com/guides/testing-library-vs-enzyme-2026)</sup>

## References

1. [Introducing the react-testing-library, Kent C. Dodds (April 2, 2018)](https://kentcdodds.com/blog/introducing-the-react-testing-library)
2. [API | React Testing Library, Testing Library docs](https://testing-library.com/docs/react-testing-library/api/)
3. [Guiding Principles, Testing Library docs](https://testing-library.com/docs/guiding-principles/)
4. [About Queries, Testing Library docs](https://testing-library.com/docs/queries/about/)
5. [Releases, testing-library/react-testing-library, GitHub](https://github.com/testing-library/react-testing-library/releases)
6. [Testing Library vs Enzyme 2026, PkgPulse (March 8, 2026)](https://www.pkgpulse.com/guides/testing-library-vs-enzyme-2026)
7. [Accessibility, Testing Library docs](https://testing-library.com/docs/dom-testing-library/api-accessibility/)
8. [Test-Driven React, Manning](https://library.knu.edu.af/opac/temp/14281.pdf)
9. [Migrate from Enzyme, Testing Library docs](https://testing-library.com/docs/react-testing-library/migrate-from-enzyme/)
10. [Async Methods, Testing Library docs](https://testing-library.com/docs/dom-testing-library/api-async/)
11. [Testing Library organization repositories](https://sitelet.easiiodev.ai/sitelet?url=https%3A%2F%2Fgithub.com%2Ftesting-library)
12. [Cypress Testing Library, Testing Library docs](https://testing-library.com/docs/cypress-testing-library/intro/)
13. [Puppeteer Testing Library, Testing Library docs](https://testing-library.com/docs/pptr-testing-library/intro/)
14. [Testing, Vue.js guide](https://vuejs.org/guide/scaling-up/testing)
15. [Custom Queries, Testing Library docs](https://testing-library.com/docs/dom-testing-library/api-custom-queries/)
16. [Open-source notices for @testing-library/react 12.1.5, BigFix](https://support.bigfix.com/product/documents/opensource/Notices_BigFix_Remediate_V11_July2024.pdf)

---
*Initially written Oct 15, 2026*

Topic: 技术与人造世界 › 计算技术与数字系统 › 软件与编程 › Named software products and platforms › Frontend libraries and UI component frameworks

Copyright 2026 Edgepedia

License: Edgepedia Community License 1.0, https://www.edgepedia.org/edgepedia/license

Source: https://www.edgepedia.org/zh/testing-library

English original: https://www.edgepedia.org/testing-library
