Installations
npm install @testing-library/react
Score
87.6
Supply Chain
93.6
Quality
89.5
Maintenance
100
Vulnerability
100
License
Releases
Contributors
Developer
Module System
CommonJS
Statistics
19,033 Stars
525 Commits
1,106 Forks
140 Watching
4 Branches
183 Contributors
Updated on 20 Nov 2024
Languages
JavaScript (90.16%)
TypeScript (9.84%)
Total Downloads
Cumulative downloads
Total Downloads
1,498,266,027
Last day
1%
2,120,646
Compared to previous day
Last week
2.5%
10,815,203
Compared to previous week
Last month
7.5%
46,228,407
Compared to previous month
Last year
19.6%
490,291,684
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
React Testing Library
Simple and complete React DOM testing utilities that encourage good testing practices.
Table of Contents
- The problem
- The solution
- Installation
- Examples
- Hooks
- Guiding Principles
- Docs
- Issues
- Contributors
- LICENSE
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.
Installation
This module is distributed via npm which is bundled with 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 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.
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):
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})
Examples
Basic Example
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})
Complex Example
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.
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.
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.
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:
- If it relates to rendering components, it deals with DOM nodes rather than component instances, nor should it encourage dealing with component instances.
- 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 toreact-dom
. - 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
Issues
Looking to contribute? Look for the Good First Issue label.
🐛 Bugs
Please file an issue for bugs, missing documentation, or unexpected behavior.
💡 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.
❓ Questions
For questions related to using the library, please visit a support community instead of filing an issue on GitHub.
Contributors
Thanks goes to these people (emoji key):
This project follows the all-contributors specification. Contributions of any kind welcome!
LICENSE
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
2 commit(s) and 9 issue activity found in the last 90 days -- score normalized to 9
Reason
Found 17/27 approved changesets -- score normalized to 6
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: jobLevel 'actions' permission set to 'write': .github/workflows/validate.yml:70
- Warn: jobLevel 'contents' permission set to 'write': .github/workflows/validate.yml:71
- Warn: topLevel 'actions' permission set to 'write': .github/workflows/validate.yml:21
- Info: topLevel 'contents' permission set to 'read': .github/workflows/validate.yml:22
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/validate.yml:37: update your workflow using https://app.stepsecurity.io/secureworkflow/testing-library/react-testing-library/validate.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/validate.yml:40: update your workflow using https://app.stepsecurity.io/secureworkflow/testing-library/react-testing-library/validate.yml/main?enable=pin
- Warn: third-party GitHubAction not pinned by hash: .github/workflows/validate.yml:45: update your workflow using https://app.stepsecurity.io/secureworkflow/testing-library/react-testing-library/validate.yml/main?enable=pin
- Warn: third-party GitHubAction not pinned by hash: .github/workflows/validate.yml:62: update your workflow using https://app.stepsecurity.io/secureworkflow/testing-library/react-testing-library/validate.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/validate.yml:81: update your workflow using https://app.stepsecurity.io/secureworkflow/testing-library/react-testing-library/validate.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/validate.yml:84: update your workflow using https://app.stepsecurity.io/secureworkflow/testing-library/react-testing-library/validate.yml/main?enable=pin
- Warn: third-party GitHubAction not pinned by hash: .github/workflows/validate.yml:89: update your workflow using https://app.stepsecurity.io/secureworkflow/testing-library/react-testing-library/validate.yml/main?enable=pin
- Warn: third-party GitHubAction not pinned by hash: .github/workflows/validate.yml:97: update your workflow using https://app.stepsecurity.io/secureworkflow/testing-library/react-testing-library/validate.yml/main?enable=pin
- Warn: npmCommand not pinned by hash: .github/workflows/validate.yml:57
- Info: 0 out of 4 GitHub-owned GitHubAction dependencies pinned
- Info: 0 out of 4 third-party GitHubAction dependencies pinned
- Info: 0 out of 1 npmCommand dependencies pinned
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 30 are checked with a SAST tool
Score
5.3
/10
Last Scanned on 2024-11-18
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 MoreOther packages similar to @testing-library/react
@testing-library/user-event
Fire events the same way the user does
@testing-library/react-hooks
Simple and complete React hooks testing utilities that encourage good testing practices.
@testing-library/react-native
Simple and complete React Native testing utilities that encourage good testing practices.
@testing-library/jest-native
Custom jest matchers to test the state of React Native