Skip to main content

ByTestId

getByTestId, queryByTestId, getAllByTestId, queryAllByTestId, findByTestId, findAllByTestId

API

getByTestId(
// If you're using `screen`, then skip the container argument:
container: HTMLElement,
text: TextMatch,
options?: {
exact?: boolean = true,
normalizer?: NormalizerFn,
}): HTMLElement

A shortcut to container.querySelector(`[data-testid="${yourId}"]`) (and it also accepts a TextMatch).

<div data-testid="custom-element" />
import {screen} from '@testing-library/dom'

const element = screen.getByTestId('custom-element')

In the spirit of the guiding principles, it is recommended to use this only after the other queries don't work for your use case. Using data-testid attributes do not resemble how your software is used and should be avoided if possible. That said, they are way better than querying based on DOM structure or styling css class names. Learn more about data-testids from the blog post "Making your UI tests resilient to change"

Options

TextMatch options

Overriding data-testid

The ...ByTestId functions in DOM Testing Library use the attribute data-testid by default, following the precedent set by React Native Web which uses a testID prop to emit a data-testid attribute on the element, and we recommend you adopt that attribute where possible. But if you already have an existing codebase that uses a different attribute for this purpose, you can override this value via configure({testIdAttribute: 'data-my-test-attribute'}).