docs/dom-testing-library/cheatsheet.mdx
A short guide to all the exported functions in DOM Testing Library
| 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 |
See Async API. Remember to await or
.then() the result of async functions in your tests!
Deprecated since v7.0.0:
- wait (Promise) retry the function within until it stops throwing or times out
- waitForElement (Promise) retry the function until it returns an element or an array of elements. The
findByandfindAllByqueries are async and retry until the query returns successfully, or when the query times out; they wrapwaitForElement- waitForDomChange (Promise) retry the function each time the DOM is changed
See Considerations for fireEvent, Events API
fireEvent(node, event)fireEvent.click(node)See Querying Within Elements, Config API
React Testing Library's render
method): within(node).getByText("hello")configure({testIdAttribute: 'my-data-test-id'})Given the following HTML:
<div>Hello World</div>
Will find the div:
// Matching a string:
getByText(container, 'Hello World') // full string match
getByText(container, 'llo Worl', {exact: false}) // substring match
getByText(container, 'hello world', {exact: false}) // ignore case
// Matching a regex:
getByText(container, /World/) // substring match
getByText(container, /world/i) // substring match, ignore case
getByText(container, /^hello world$/i) // full string match, ignore case
getByText(container, /Hello W?oRlD/i) // advanced regex
// Matching with a custom function:
getByText(container, (content, element) => content.startsWith('Hello'))
Given a button that updates the page after some time:
test('loads items eventually', async () => {
// Click button
fireEvent.click(getByText(node, 'Load'))
// Wait for page to update with query text
const items = await findAllByText(node, /Item #[0-9]: /)
expect(items).toHaveLength(10)
})