Skip to content

Testing Library ​

Using wrapper as the variable name for the return value from render ​

Rule: Do not use wrapper as the variable name for the return value of render. Destructure what you need directly, or use view.

js
// ❌
const wrapper = render(<Example prop="1" />)
wrapper.rerender(<Example prop="2" />)

// ✅
const {rerender} = render(<Example prop="1" />)
rerender(<Example prop="2" />)

The name wrapper is old cruft from enzyme and we don't need that here. The return value from render is not "wrapping" anything. It's simply a collection of utilities that you should actually not often need anyway.

Advice

Destructure what you need from render or call it view.

Using cleanup ​

Rule: Do not manually call cleanup. It runs automatically.

js
// ❌
import {render, screen, cleanup} from '@testing-library/react'

afterEach(cleanup)

// ✅
import {render, screen} from '@testing-library/react'

For a long time now cleanup happens automatically (supported for most major testing frameworks) and you no longer need to worry about it. Learn more.

Not using screen ​

Rule: Always use screen for queries and debugging. Do not destructure query methods from the render return value.

js
// ❌
const {getByRole} = render(<Example />)
const errorMessageNode = getByRole('alert')

// ✅
render(<Example />)
const errorMessageNode = screen.getByRole('alert')

screenwas added in DOM Testing Library v6.11.0 (which means you should have access to it in @testing-library/react@>=9). It comes from the same import statement you get render from:

js
import {render, screen} from '@testing-library/react'

The benefit of using screen is you no longer need to keep the render call destructure up-to-date as you add/remove the queries you need. You only need to type screen. and let your editor's magic autocomplete take care of the rest.

Using the wrong assertion ​

Rule: Use jest-dom matchers (e.g. toBeDisabled()) instead of asserting against DOM properties directly.

js
const button = screen.getByRole('button', {name: /disabled button/i})

// ❌
expect(button.disabled).toBe(true)

// ✅
expect(button).toBeDisabled()

That toBeDisabled assertion comes from jest-dom. It's strongly recommended to use jest-dom because the error messages you get with it are much better.

Wrapping things in act unnecessarily ​

Rule: Do not wrap render or fireEvent calls in act. They are already wrapped internally.

js
// ❌
act(() => {
  render(<Example />)
})

const input = screen.getByRole('textbox', {name: /choose a fruit/i})
act(() => {
  fireEvent.keyDown(input, {key: 'ArrowDown'})
})

// ✅
render(<Example />)
const input = screen.getByRole('textbox', {name: /choose a fruit/i})
fireEvent.keyDown(input, {key: 'ArrowDown'})

render and fireEvent are already wrapped in act, so wrapping them again does nothing useful. Most of the time, if you're seeing an act warning, it's telling you that something unexpected is happening in your test — not something to be silenced.

Using the wrong query ​

Rule: Query elements by accessible role or text. Do not use data-testid or CSS selectors unless no accessible alternative exists.

js
// ❌
// <label>Username</label><input data-testid="username" />
screen.getByTestId('username')

// ✅
// <label for="username">Username</label><input id="username" type="text" />
screen.getByRole('textbox', {name: /username/i})

Use the "Which query should I use?" page for the recommended query priority order.

Advice

Read and follow the recommendations in The "Which Query Should I Use" Guide.

Using container to query for elements ​

Rule: Do not query elements via container.querySelector. Use screen queries instead.

js
// ❌
const {container} = render(<Example />)
const button = container.querySelector('.btn-primary')
expect(button).toHaveTextContent(/click me/i)

// ✅
render(<Example />)
screen.getByRole('button', {name: /click me/i})

Querying via querySelector loses confidence that your users can interact with your UI, makes the test harder to read, and causes it to break more frequently.

Not querying by text ​

Rule: Query by the actual visible text content rather than test IDs or other mechanisms.

js
// ❌
screen.getByTestId('submit-button')

// ✅
screen.getByRole('button', {name: /submit/i})

Querying by text gives you confidence that translations are applied correctly, and makes tests easier to write and read. The cost of a content change breaking a test is very low — it's easy to triage and easy to fix.

Not using *ByRole most of the time ​

Rule: Prefer *ByRole queries over all other query types. They validate accessibility and produce the most helpful failure messages.

js
// ❌
screen.getByText(/hello world/i)
// may fail if text is split across child elements

// ✅
screen.getByRole('button', {name: /hello world/i})
// works even when text is split across spans

The name option matches the element's "Accessible Name" — what screen readers announce — and works even when text is split across child elements. When a role query fails, it logs all available roles in the rendered output, making debugging straightforward.

Advice

Read and follow the recommendations in The "Which Query Should I Use" Guide.

Adding aria-, role, and other accessibility attributes incorrectly ​

Rule: Do not add aria- or role attributes to elements that already have the correct implicit role.

js
// ❌
render(<button role="button">Click me</button>)

// ✅
render(<button>Click me</button>)

Adding accessibility attributes unnecessarily is not only redundant — it can confuse screen readers. Only use them when semantic HTML doesn't satisfy your use case.

Note

To make inputs accessible via a "role" you'll want to specify the type attribute.

Advice

Avoid adding unnecessary or incorrect accessibility attributes.

Not using @testing-library/user-event ​

Rule: Use @testing-library/user-event over fireEvent for all user interactions.

js
// ❌
fireEvent.change(input, {target: {value: 'hello world'}})

// ✅
userEvent.type(input, 'hello world')

@testing-library/user-event is built on top of fireEvent but fires the full sequence of events a real user would trigger — keyDown, keyPress, keyUp for each character, focus events, etc. This catches bugs that fireEvent misses.

Advice

Use @testing-library/user-event over fireEvent where possible.

Using query* variants for anything except checking for non-existence ​

Rule: Only use query* variants when asserting that an element does NOT exist. Use get* or find* in all other cases.

js
// ❌
expect(screen.queryByRole('alert')).toBeInTheDocument()

// ✅
expect(screen.getByRole('alert')).toBeInTheDocument()
expect(screen.queryByRole('alert')).not.toBeInTheDocument()

query* returns null when nothing is found rather than throwing. This is only useful for asserting absence. For positive assertions, use get* or find* — they throw a helpful error with the full DOM when the element is missing.

Advice

Only use the query* variants for asserting that an element cannot be found.

Using waitFor to wait for elements that can be queried with find* ​

Rule: Use find* queries instead of wrapping get* in waitFor.

js
// ❌
const submitButton = await waitFor(() =>
  screen.getByRole('button', {name: /submit/i}),
)

// ✅
const submitButton = await screen.findByRole('button', {name: /submit/i})

find* queries are waitFor + get* combined. The second form is simpler and produces better error messages.

Advice

Use find* any time you want to query for something that may not be available right away.

Passing an empty callback to waitFor ​

Rule: Always pass a specific assertion inside waitFor. Do not pass an empty callback.

js
// ❌
await waitFor(() => {})
expect(window.fetch).toHaveBeenCalledWith('foo')

// ✅
await waitFor(() => expect(window.fetch).toHaveBeenCalledWith('foo'))

An empty waitFor callback might work today because it only needs one tick of the event loop, but it produces a fragile test that can silently break when async logic changes.

Advice

Wait for a specific assertion inside waitFor.

Having multiple assertions in a single waitFor callback ​

Rule: Only put one assertion inside a waitFor callback.

js
// ❌
await waitFor(() => {
  expect(window.fetch).toHaveBeenCalledWith('foo')
  expect(window.fetch).toHaveBeenCalledTimes(1)
})

// ✅
await waitFor(() => expect(window.fetch).toHaveBeenCalledWith('foo'))
expect(window.fetch).toHaveBeenCalledTimes(1)

With multiple assertions, a failure in the second one means waiting for the full timeout before the test fails. A single assertion fails fast and points directly at the problem.

Advice

Only put one assertion in a callback.

Performing side-effects in waitFor ​

Rule: Do not perform side-effects (e.g. fireEvent, userEvent) inside waitFor. Only assertions belong in the callback.

js
// ❌
await waitFor(() => {
  fireEvent.keyDown(input, {key: 'ArrowDown'})
  expect(screen.getAllByRole('listitem')).toHaveLength(3)
})

// ✅
fireEvent.keyDown(input, {key: 'ArrowDown'})
await waitFor(() => {
  expect(screen.getAllByRole('listitem')).toHaveLength(3)
})

waitFor retries its callback on an interval and on DOM mutations. A side-effect inside the callback will execute multiple times, which is almost never what you want.

Advice

Put side-effects outside waitFor callbacks and reserve the callback for assertions only.

Using get* variants as assertions ​

Rule: Always wrap get* queries in an explicit expect() assertion. Do not rely on the query throwing as an implicit assertion.

js
// ❌
screen.getByRole('alert', {name: /error/i})

// ✅
expect(screen.getByRole('alert', {name: /error/i})).toBeInTheDocument()

A bare get* call will never fail as an assertion — if the element is missing it throws before the assertion runs, and if it's present the assertion is implicitly always true. Make the intent explicit with expect.

Advice

If you want to assert that something exists, make that assertion explicit.

Made with ❤️ by the Luna team