Which query should I use?
Priority#
Based on the Guiding Principles, your test should resemble how users interact with your code (component, page, etc.) as much as possible. With this in mind, we recommend this order of priority:
- Queries Accessible to Everyone queries that reflect the experience of
visual/mouse users as well as those that use assistive technology
getByLabelText: Only really good for form fields, but this is the number one method a user finds those elements, so it should be your top preference.getByPlaceholderText: A placeholder is not a substitute for a label. But if that's all you have, then it's better than alternatives.getByRole: This can be used to query every element that is exposed in the accessibility tree. With thenameoption you can filter the returned elements by their accessible name. This should be your top preference for interactive elements such as buttons.getByText: Not useful for forms, but this is the number 1 method a user finds most non-interactive elements (listitems or divs).getByDisplayValue: The current value of a form element can be useful when navigating a page with filled-in values.
- Semantic Queries HTML5 and ARIA compliant selectors. Note that the user
experience of interacting with these attributes varies greatly across
browsers and assistive technology.
getByAltText: If your element is one which supportsalttext (img,area, andinput), then you can use this to find that element.getByTitle: The title attribute is not consistently read by screenreaders, and is not visible by default for sighted users
- Test IDs
getByTestId: The user cannot see (or hear) these, so this is only recommended for cases where you can't match by role or text or it doesn't make sense (e.g. the text is dynamic).
Manual Queries#
On top of the queries provided by the testing library, you can use the regular
querySelector DOM API
to query elements. Note that using this as an escape hatch to query by class or
id is a bad practice because users can't see or identify these attributes. Use a
testid if you have to.