react-testing-library

react-testing-library

React 组件测试利器 推崇最佳实践

React Testing Library 为 React 组件测试提供轻量级解决方案。基于 react-dom 和 test-utils,它提供简洁实用的函数,倡导更优测试实践。其核心理念是让测试尽可能贴近软件实际使用场景,从而增强可信度。该库通过直观的 API 实现 DOM 查询和交互,有助于开发者编写易维护的测试,聚焦组件功能而非实现细节。

React测试DOM组件JavaScriptGithub开源项目
<div align="center"> <h1>React Testing Library</h1> <a href="https://www.emojione.com/emoji/1f410"> <img height="80" width="80" alt="goat" src="https://raw.githubusercontent.com/testing-library/react-testing-library/main/other/goat.png" /> </a> <p>Simple and complete React DOM testing utilities that encourage good testing practices.</p> <br />

Read The Docs | Edit the docs

<br /> </div> <hr /> <!-- prettier-ignore-start -->

[![Build Status][build-badge]][build] [![Code Coverage][coverage-badge]][coverage] [![version][version-badge]][package] [![downloads][downloads-badge]][npmtrends] [![MIT License][license-badge]][license] ![All Contributors][all-contributors-badge] [![PRs Welcome][prs-badge]][prs] [![Code of Conduct][coc-badge]][coc] [![Discord][discord-badge]][discord]

[![Watch on GitHub][github-watch-badge]][github-watch] [![Star on GitHub][github-star-badge]][github-star] [![Tweet][twitter-badge]][twitter]

<!-- prettier-ignore-end --> <div align="center"> <a href="https://testingjavascript.com"> <img width="500" alt="TestingJavaScript.com Learn the smart, efficient way to test any JavaScript application." src="https://raw.githubusercontent.com/testing-library/react-testing-library/main/other/testingjavascript.jpg" /> </a> </div>

Table of Contents

<!-- START doctoc generated TOC please keep comment here to allow auto update --> <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE --> <!-- END doctoc generated TOC please keep comment here to allow auto update -->

The problem

You want to write maintainable tests for your React components. As a part of this goal, you want your tests to avoid including implementation details of your components and rather focus on making your tests give you the confidence for which they are intended. As part of this, you want your testbase to be maintainable in the long run so refactors of your components (changes to implementation but not functionality) don't break your tests and slow you and your team down.

The solution

The React Testing Library is a very lightweight solution for testing React components. It provides light utility functions on top of react-dom and react-dom/test-utils, in a way that encourages better testing practices. Its primary guiding principle is:

[The more your tests resemble the way your software is used, the more confidence they can give you.][guiding-principle]

Installation

This module is distributed via [npm][npm] which is bundled with [node][node] and should be installed as one of your project's devDependencies.
Starting from RTL version 16, you'll also need to install @testing-library/dom:

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

or

for installation via [yarn][yarn]

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

This library has peerDependencies listings for react, react-dom and starting from RTL version 16 also @testing-library/dom.

React Testing Library versions 13+ require React v18. If your project uses an older version of React, be sure to install version 12:

npm install --save-dev @testing-library/react@12


yarn add --dev @testing-library/react@12

You may also be interested in installing @testing-library/jest-dom so you can use the custom jest matchers.

Docs

Suppressing unnecessary warnings on React DOM 16.8

There is a known compatibility issue with React DOM 16.8 where you will see the following warning:

Warning: An update to ComponentName inside a test was not wrapped in act(...).

If you cannot upgrade to React DOM 16.9, you may suppress the warnings by adding the following snippet to your test configuration (learn more):

// this is just a little hack to silence a warning that we'll get until we // upgrade to 16.9. See also: https://github.com/facebook/react/pull/14853 const originalError = console.error beforeAll(() => { console.error = (...args) => { if (/Warning.*not wrapped in act/.test(args[0])) { return } originalError.call(console, ...args) } }) afterAll(() => { console.error = originalError })

Examples

Basic Example

// hidden-message.js import * as React from 'react' // NOTE: React Testing Library works well with React Hooks and classes. // Your tests will be the same regardless of how you write your components. function HiddenMessage({children}) { const [showMessage, setShowMessage] = React.useState(false) return ( <div> <label htmlFor="toggle">Show Message</label> <input id="toggle" type="checkbox" onChange={e => setShowMessage(e.target.checked)} checked={showMessage} /> {showMessage ? children : null} </div> ) } export default HiddenMessage
// __tests__/hidden-message.js // these imports are something you'd normally configure Jest to import for you // automatically. Learn more in the setup docs: https://testing-library.com/docs/react-testing-library/setup#cleanup import '@testing-library/jest-dom' // NOTE: jest-dom adds handy assertions to Jest and is recommended, but not required import * as React from 'react' import {render, fireEvent, screen} from '@testing-library/react' import HiddenMessage from '../hidden-message' test('shows the children when the checkbox is checked', () => { const testMessage = 'Test Message' render(<HiddenMessage>{testMessage}</HiddenMessage>) // query* functions will return the element or null if it cannot be found // get* functions will return the element or throw an error if it cannot be found expect(screen.queryByText(testMessage)).toBeNull() // the queries can accept a regex to make your selectors more resilient to content tweaks and changes. fireEvent.click(screen.getByLabelText(/show/i)) // .toBeInTheDocument() is an assertion that comes from jest-dom // otherwise you could use .toBeDefined() expect(screen.getByText(testMessage)).toBeInTheDocument() })

Complex Example

// login.js import * as React from 'react' function Login() { const [state, setState] = React.useReducer((s, a) => ({...s, ...a}), { resolved: false, loading: false, error: null, }) function handleSubmit(event) { event.preventDefault() const {usernameInput, passwordInput} = event.target.elements setState({loading: true, resolved: false, error: null}) window .fetch('/api/login', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ username: usernameInput.value, password: passwordInput.value, }), }) .then(r => r.json().then(data => (r.ok ? data : Promise.reject(data)))) .then( user => { setState({loading: false, resolved: true, error: null}) window.localStorage.setItem('token', user.token) }, error => { setState({loading: false, resolved: false, error: error.message}) }, ) } return ( <div> <form onSubmit={handleSubmit}> <div> <label htmlFor="usernameInput">Username</label> <input id="usernameInput" /> </div> <div> <label htmlFor="passwordInput">Password</label> <input id="passwordInput" type="password" /> </div> <button type="submit">Submit{state.loading ? '...' : null}</button> </form> {state.error ? <div role="alert">{state.error}</div> : null} {state.resolved ? ( <div role="alert">Congrats! You're signed in!</div> ) : null} </div> ) } export default Login
// __tests__/login.js // again, these first two imports are something you'd normally handle in // your testing framework configuration rather than importing them in every file. import '@testing-library/jest-dom' import * as React from 'react' // import API mocking utilities from Mock Service Worker. import {rest} from 'msw' import {setupServer} from 'msw/node' // import testing utilities import {render, fireEvent, screen} from '@testing-library/react' import Login from '../login' const fakeUserResponse = {token: 'fake_user_token'} const server = setupServer( rest.post('/api/login', (req, res, ctx) => { return res(ctx.json(fakeUserResponse)) }), ) beforeAll(() => server.listen()) afterEach(() => { server.resetHandlers() window.localStorage.removeItem('token') }) afterAll(() => server.close()) test('allows the user to login successfully', async () => { render(<Login />) // fill out the form fireEvent.change(screen.getByLabelText(/username/i), { target: {value: 'chuck'}, }) fireEvent.change(screen.getByLabelText(/password/i), { target: {value: 'norris'}, }) fireEvent.click(screen.getByText(/submit/i)) // just like a manual tester, we'll instruct our test to wait for the alert // to show up before continuing with our assertions. const alert = await screen.findByRole('alert') // .toHaveTextContent() comes from jest-dom's assertions // otherwise you could use expect(alert.textContent).toMatch(/congrats/i) // but jest-dom will give you better error messages which is why it's recommended expect(alert).toHaveTextContent(/congrats/i) expect(window.localStorage.getItem('token')).toEqual(fakeUserResponse.token) }) test('handles server exceptions', async () => { // mock the server error response for this test suite only. server.use( rest.post('/api/login', (req, res, ctx) => { return res(ctx.status(500), ctx.json({message: 'Internal server error'})) }), ) render(<Login />) // fill out the form fireEvent.change(screen.getByLabelText(/username/i), { target: {value: 'chuck'}, }) fireEvent.change(screen.getByLabelText(/password/i), { target: {value: 'norris'}, }) fireEvent.click(screen.getByText(/submit/i)) // wait for the error message const alert = await screen.findByRole('alert') expect(alert).toHaveTextContent(/internal server error/i) expect(window.localStorage.getItem('token')).toBeNull() })

We recommend using Mock Service Worker library to declaratively mock API communication in your tests instead of stubbing window.fetch, or relying on third-party adapters.

More Examples

We're in the process of moving examples to the docs site

You'll find runnable examples of testing with different libraries in the react-testing-library-examples codesandbox. Some included are:

Hooks

If you are interested in testing a custom hook, check out [React Hooks Testing Library][react-hooks-testing-library].

NOTE: it is not recommended to test single-use custom hooks in isolation from the components where it's being used. It's better to test the component that's using the hook rather than the hook itself. The React Hooks Testing Library is intended to be used for reusable hooks/libraries.

Guiding Principles

[The more your tests resemble the way your software is used, the more confidence they can give you.][guiding-principle]

We try to only expose methods and utilities that encourage you to write tests that closely resemble how your React components are used.

Utilities are included in this project based on the following guiding principles:

  1. If it relates to rendering components, it deals with DOM nodes rather than component instances, nor should it encourage dealing with component instances.
  2. It should be generally useful for testing individual React components or full React applications. While this library is focused on react-dom, utilities could be included even if they don't directly relate to react-dom.
  3. Utility implementations and APIs should be simple and flexible.

Most importantly, we want React Testing Library to be pretty light-weight, simple, and easy to understand.

Docs

Read The Docs | Edit the docs

Issues

Looking to contribute? Look for the [Good First Issue][good-first-issue] label.

🐛 Bugs

Please file an issue for bugs, missing documentation, or unexpected behavior.

[See Bugs][bugs]

💡 Feature Requests

Please file an issue to suggest new features. Vote on feature requests by adding a 👍. This helps maintainers prioritize what to work on.

[See Feature Requests][requests]

❓ Questions

For questions related to using the library, please visit a support community instead of filing an issue on GitHub.

  • [Discord][discord]
  • [Stack Overflow][stackoverflow]

Contributors

Thanks goes to these people ([emoji key][emojis]):

<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section --> <!-- prettier-ignore-start --> <!-- markdownlint-disable --> <table> <tbody> <tr> <td align="center" valign="top" width="14.28%"><a href="https://kentcdodds.com"><img src="https://avatars.githubusercontent.com/u/1500684?v=3?s=100" width="100px;" alt="Kent C. Dodds"/><br /><sub><b>Kent C. Dodds</b></sub></a><br /><a href="https://github.com/testing-library/react-testing-library/commits?author=kentcdodds" title="Code">💻</a> <a href="https://github.com/testing-library/react-testing-library/commits?author=kentcdodds" title="Documentation">📖</a> <a href="#infra-kentcdodds" title="Infrastructure (Hosting, Build-Tools, etc)">🚇</a> <a href="https://github.com/testing-library/react-testing-library/commits?author=kentcdodds" title="Tests">⚠️</a></td> <td align="center" valign="top" width="14.28%"><a href="http://audiolion.github.io"><img src="https://avatars1.githubusercontent.com/u/2430381?v=4?s=100" width="100px;" alt="Ryan Castner"/><br /><sub><b>Ryan Castner</b></sub></a><br /><a href="https://github.com/testing-library/react-testing-library/commits?author=audiolion" title="Documentation">📖</a></td> <td align="center" valign="top" width="14.28%"><a href="https://www.dnlsandiego.com"><img src="https://avatars0.githubusercontent.com/u/8008023?v=4?s=100" width="100px;" alt="Daniel Sandiego"/><br /><sub><b>Daniel Sandiego</b></sub></a><br /><a href="https://github.com/testing-library/react-testing-library/commits?author=dnlsandiego" title="Code">💻</a></td> <td align="center" valign="top" width="14.28%"><a href="https://github.com/Miklet"><img src="https://avatars2.githubusercontent.com/u/12592677?v=4?s=100" width="100px;" alt="Paweł Mikołajczyk"/><br /><sub><b>Paweł Mikołajczyk</b></sub></a><br /><a href="https://github.com/testing-library/react-testing-library/commits?author=Miklet" title="Code">💻</a></td> <td align="center" valign="top" width="14.28%"><a

编辑推荐精选

Trae

Trae

字节跳动发布的AI编程神器IDE

Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。

AI工具TraeAI IDE协作生产力转型热门
问小白

问小白

全能AI智能助手,随时解答生活与工作的多样问题

问小白,由元石科技研发的AI智能助手,快速准确地解答各种生活和工作问题,包括但不限于搜索、规划和社交互动,帮助用户在日常生活中提高效率,轻松管理个人事务。

热门AI助手AI对话AI工具聊天机器人
Transly

Transly

实时语音翻译/同声传译工具

Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。

讯飞智文

讯飞智文

一键生成PPT和Word,让学习生活更轻松

讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。

AI办公办公工具AI工具讯飞智文AI在线生成PPTAI撰写助手多语种文档生成AI自动配图热门
讯飞星火

讯飞星火

深度推理能力全新升级,全面对标OpenAI o1

科大讯飞的星火大模型,支持语言理解、知识问答和文本创作等多功能,适用于多种文件和业务场景,提升办公和日常生活的效率。讯飞星火是一个提供丰富智能服务的平台,涵盖科技资讯、图像创作、写作辅助、编程解答、科研文献解读等功能,能为不同需求的用户提供便捷高效的帮助,助力用户轻松获取信息、解决问题,满足多样化使用场景。

热门AI开发模型训练AI工具讯飞星火大模型智能问答内容创作多语种支持智慧生活
Spark-TTS

Spark-TTS

一种基于大语言模型的高效单流解耦语音令牌文本到语音合成模型

Spark-TTS 是一个基于 PyTorch 的开源文本到语音合成项目,由多个知名机构联合参与。该项目提供了高效的 LLM(大语言模型)驱动的语音合成方案,支持语音克隆和语音创建功能,可通过命令行界面(CLI)和 Web UI 两种方式使用。用户可以根据需求调整语音的性别、音高、速度等参数,生成高质量的语音。该项目适用于多种场景,如有声读物制作、智能语音助手开发等。

咔片PPT

咔片PPT

AI助力,做PPT更简单!

咔片是一款轻量化在线演示设计工具,借助 AI 技术,实现从内容生成到智能设计的一站式 PPT 制作服务。支持多种文档格式导入生成 PPT,提供海量模板、智能美化、素材替换等功能,适用于销售、教师、学生等各类人群,能高效制作出高品质 PPT,满足不同场景演示需求。

讯飞绘文

讯飞绘文

选题、配图、成文,一站式创作,让内容运营更高效

讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。

热门AI辅助写作AI工具讯飞绘文内容运营AI创作个性化文章多平台分发AI助手
材料星

材料星

专业的AI公文写作平台,公文写作神器

AI 材料星,专业的 AI 公文写作辅助平台,为体制内工作人员提供高效的公文写作解决方案。拥有海量公文文库、9 大核心 AI 功能,支持 30 + 文稿类型生成,助力快速完成领导讲话、工作总结、述职报告等材料,提升办公效率,是体制打工人的得力写作神器。

openai-agents-python

openai-agents-python

OpenAI Agents SDK,助力开发者便捷使用 OpenAI 相关功能。

openai-agents-python 是 OpenAI 推出的一款强大 Python SDK,它为开发者提供了与 OpenAI 模型交互的高效工具,支持工具调用、结果处理、追踪等功能,涵盖多种应用场景,如研究助手、财务研究等,能显著提升开发效率,让开发者更轻松地利用 OpenAI 的技术优势。

下拉加载更多