docs/react-testing-library/cheatsheet.mdx
A short guide to all the exported functions in React Testing Library
const = render(Component) returns:
unmount function to unmount the componentcontainer reference to the DOM node where the component is mountedDOM Testing Library, bound to the document so there
is no need to pass a node as the first argument (usually, you can use the
screen import instead)import {render, fireEvent, screen} from '@testing-library/react'
test('loads items eventually', async () => {
render(<Page />)
// Click button
fireEvent.click(screen.getByText('Load'))
// Wait for page to update with query text
const items = await screen.findAllByText(/Item #[0-9]: /)
expect(items).toHaveLength(10)
})
Difference from DOM Testing Library
The queries returned from
renderinReact Testing Libraryare the same asDOM Testing Libraryexcept they have the first argument bound to the document, so instead ofgetByText(node, 'text')you dogetByText('text')
| No Match | 1 Match | 1+ Match | Await? | |
|---|---|---|---|---|
| getBy | throw | return | throw | No |
| findBy | throw | return | throw | Yes |
| queryBy | null | return | throw | No |
| getAllBy | throw | array | array | No |
| findAllBy | throw | array | array | Yes |
| queryAllBy | [] | array | array | No |
The dom-testing-library Async API is re-exported from React Testing Library.
See Events API
fireEvent(node, event)fireEvent.click(node)act already so
most cases should not require using it manuallySee Querying Within Elements, Config API, Cleanup,
React Testing Library's render
method): within(node).getByText("hello")configure({testIdAttribute: 'my-data-test-id'})afterEach to reset DOM
between tests)Given the following HTML:
<div>Hello World</div>
Will find the div:
// Matching a string:
getByText('Hello World') // full string match
getByText('llo Worl', {exact: false}) // substring match
getByText('hello world', {exact: false}) // ignore case
// Matching a regex:
getByText(/World/) // substring match
getByText(/world/i) // substring match, ignore case
getByText(/^hello world$/i) // full string match, ignore case
getByText(/Hello W?oRlD/i) // advanced regex
// Matching with a custom function:
getByText((content, element) => content.startsWith('Hello'))