Gathering detailed insights and metrics for @testing-library/react
Gathering detailed insights and metrics for @testing-library/react
Gathering detailed insights and metrics for @testing-library/react
Gathering detailed insights and metrics for @testing-library/react
@testing-library/react-hooks
Simple and complete React hooks testing utilities that encourage good testing practices.
@testing-library/user-event
Fire events the same way the user does
@types/testing-library__react
Stub TypeScript definitions entry for @testing-library/react, which provides its own types definitions
@testing-library/react-native
Simple and complete React Native testing utilities that encourage good testing practices.
π Simple and complete React DOM testing utilities that encourage good testing practices.
npm install @testing-library/react
Typescript
Module System
Min. Node Version
Node Version
NPM Version
85.4
Supply Chain
94.4
Quality
93.4
Maintenance
100
Vulnerability
100
License
JavaScript (90.14%)
TypeScript (9.86%)
Total Downloads
1,546,679,488
Last Day
1,268,257
Last Week
9,649,851
Last Month
44,004,627
Last Year
500,163,338
19,084 Stars
526 Commits
1,112 Forks
139 Watching
4 Branches
183 Contributors
Latest Version
16.1.0
Package Id
@testing-library/react@16.1.0
Unpacked Size
321.73 kB
Size
44.49 kB
File Count
26
NPM Version
6.14.18
Node Version
14.21.3
Publised On
05 Dec 2024
Cumulative downloads
Total Downloads
Last day
-37%
1,268,257
Compared to previous day
Last week
-11.9%
9,649,851
Compared to previous week
Last month
-1%
44,004,627
Compared to previous month
Last year
20.6%
500,163,338
Compared to previous year
Simple and complete React DOM testing utilities that encourage good testing practices.
[![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]
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 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]
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.
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):
1// this is just a little hack to silence a warning that we'll get until we 2// upgrade to 16.9. See also: https://github.com/facebook/react/pull/14853 3const originalError = console.error 4beforeAll(() => { 5 console.error = (...args) => { 6 if (/Warning.*not wrapped in act/.test(args[0])) { 7 return 8 } 9 originalError.call(console, ...args) 10 } 11}) 12 13afterAll(() => { 14 console.error = originalError 15})
1// hidden-message.js 2import * as React from 'react' 3 4// NOTE: React Testing Library works well with React Hooks and classes. 5// Your tests will be the same regardless of how you write your components. 6function HiddenMessage({children}) { 7 const [showMessage, setShowMessage] = React.useState(false) 8 return ( 9 <div> 10 <label htmlFor="toggle">Show Message</label> 11 <input 12 id="toggle" 13 type="checkbox" 14 onChange={e => setShowMessage(e.target.checked)} 15 checked={showMessage} 16 /> 17 {showMessage ? children : null} 18 </div> 19 ) 20} 21 22export default HiddenMessage
1// __tests__/hidden-message.js 2// these imports are something you'd normally configure Jest to import for you 3// automatically. Learn more in the setup docs: https://testing-library.com/docs/react-testing-library/setup#cleanup 4import '@testing-library/jest-dom' 5// NOTE: jest-dom adds handy assertions to Jest and is recommended, but not required 6 7import * as React from 'react' 8import {render, fireEvent, screen} from '@testing-library/react' 9import HiddenMessage from '../hidden-message' 10 11test('shows the children when the checkbox is checked', () => { 12 const testMessage = 'Test Message' 13 render(<HiddenMessage>{testMessage}</HiddenMessage>) 14 15 // query* functions will return the element or null if it cannot be found 16 // get* functions will return the element or throw an error if it cannot be found 17 expect(screen.queryByText(testMessage)).toBeNull() 18 19 // the queries can accept a regex to make your selectors more resilient to content tweaks and changes. 20 fireEvent.click(screen.getByLabelText(/show/i)) 21 22 // .toBeInTheDocument() is an assertion that comes from jest-dom 23 // otherwise you could use .toBeDefined() 24 expect(screen.getByText(testMessage)).toBeInTheDocument() 25})
1// login.js 2import * as React from 'react' 3 4function Login() { 5 const [state, setState] = React.useReducer((s, a) => ({...s, ...a}), { 6 resolved: false, 7 loading: false, 8 error: null, 9 }) 10 11 function handleSubmit(event) { 12 event.preventDefault() 13 const {usernameInput, passwordInput} = event.target.elements 14 15 setState({loading: true, resolved: false, error: null}) 16 17 window 18 .fetch('/api/login', { 19 method: 'POST', 20 headers: {'Content-Type': 'application/json'}, 21 body: JSON.stringify({ 22 username: usernameInput.value, 23 password: passwordInput.value, 24 }), 25 }) 26 .then(r => r.json().then(data => (r.ok ? data : Promise.reject(data)))) 27 .then( 28 user => { 29 setState({loading: false, resolved: true, error: null}) 30 window.localStorage.setItem('token', user.token) 31 }, 32 error => { 33 setState({loading: false, resolved: false, error: error.message}) 34 }, 35 ) 36 } 37 38 return ( 39 <div> 40 <form onSubmit={handleSubmit}> 41 <div> 42 <label htmlFor="usernameInput">Username</label> 43 <input id="usernameInput" /> 44 </div> 45 <div> 46 <label htmlFor="passwordInput">Password</label> 47 <input id="passwordInput" type="password" /> 48 </div> 49 <button type="submit">Submit{state.loading ? '...' : null}</button> 50 </form> 51 {state.error ? <div role="alert">{state.error}</div> : null} 52 {state.resolved ? ( 53 <div role="alert">Congrats! You're signed in!</div> 54 ) : null} 55 </div> 56 ) 57} 58 59export default Login
1// __tests__/login.js 2// again, these first two imports are something you'd normally handle in 3// your testing framework configuration rather than importing them in every file. 4import '@testing-library/jest-dom' 5import * as React from 'react' 6// import API mocking utilities from Mock Service Worker. 7import {rest} from 'msw' 8import {setupServer} from 'msw/node' 9// import testing utilities 10import {render, fireEvent, screen} from '@testing-library/react' 11import Login from '../login' 12 13const fakeUserResponse = {token: 'fake_user_token'} 14const server = setupServer( 15 rest.post('/api/login', (req, res, ctx) => { 16 return res(ctx.json(fakeUserResponse)) 17 }), 18) 19 20beforeAll(() => server.listen()) 21afterEach(() => { 22 server.resetHandlers() 23 window.localStorage.removeItem('token') 24}) 25afterAll(() => server.close()) 26 27test('allows the user to login successfully', async () => { 28 render(<Login />) 29 30 // fill out the form 31 fireEvent.change(screen.getByLabelText(/username/i), { 32 target: {value: 'chuck'}, 33 }) 34 fireEvent.change(screen.getByLabelText(/password/i), { 35 target: {value: 'norris'}, 36 }) 37 38 fireEvent.click(screen.getByText(/submit/i)) 39 40 // just like a manual tester, we'll instruct our test to wait for the alert 41 // to show up before continuing with our assertions. 42 const alert = await screen.findByRole('alert') 43 44 // .toHaveTextContent() comes from jest-dom's assertions 45 // otherwise you could use expect(alert.textContent).toMatch(/congrats/i) 46 // but jest-dom will give you better error messages which is why it's recommended 47 expect(alert).toHaveTextContent(/congrats/i) 48 expect(window.localStorage.getItem('token')).toEqual(fakeUserResponse.token) 49}) 50 51test('handles server exceptions', async () => { 52 // mock the server error response for this test suite only. 53 server.use( 54 rest.post('/api/login', (req, res, ctx) => { 55 return res(ctx.status(500), ctx.json({message: 'Internal server error'})) 56 }), 57 ) 58 59 render(<Login />) 60 61 // fill out the form 62 fireEvent.change(screen.getByLabelText(/username/i), { 63 target: {value: 'chuck'}, 64 }) 65 fireEvent.change(screen.getByLabelText(/password/i), { 66 target: {value: 'norris'}, 67 }) 68 69 fireEvent.click(screen.getByText(/submit/i)) 70 71 // wait for the error message 72 const alert = await screen.findByRole('alert') 73 74 expect(alert).toHaveTextContent(/internal server error/i) 75 expect(window.localStorage.getItem('token')).toBeNull() 76})
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.
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:
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.
[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:
react-dom
,
utilities could be included even if they don't directly relate to
react-dom
.Most importantly, we want React Testing Library to be pretty light-weight, simple, and easy to understand.
Looking to contribute? Look for the [Good First Issue][good-first-issue] label.
Please file an issue for bugs, missing documentation, or unexpected behavior.
[See Bugs][bugs]
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]
For questions related to using the library, please visit a support community instead of filing an issue on GitHub.
Thanks goes to these people ([emoji key][emojis]):
No vulnerabilities found.
Reason
1 commit(s) and 15 issue activity found in the last 90 days -- score normalized to 10
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
Reason
Found 16/27 approved changesets -- score normalized to 5
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
project is not fuzzed
Details
Reason
security policy file not detected
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-12-16
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More