What types of selectors does RTL provide?
React Testing Library provides several groups of selectors. Their philosophy is to look for elements the way a user would, rather than by technical details.
1) By accessibility (primary and recommended)
These selectors imitate the behavior of users with screen readers and are considered the most correct.
| Method | What it looks for |
|---|---|
getByRole | by the element's role, button, link, heading, etc. |
getByLabelText | by the label text on forms |
getByPlaceholderText | by the placeholder |
getByText | by the visible text |
getByDisplayValue | by the value of an input field |
Example:
js
getByRole("button", { name: /send/i });2) By alt text and title
Useful for images and icons.
| Method | What it looks for |
|---|---|
getByAltText | by the image's alt |
getByTitle | by the title attribute |
3) By test-id (as a last resort)
Used only when there are no other options.
| Method | What it looks for |
|---|---|
getByTestId | by data-testid="…" |
RTL considers this a last resort, because such tests are closer to the implementation than to the behavior.
4) Async and multiple versions of the same methods
All selectors have variants:
| Prefix | What it means |
|---|---|
getBy… | find the element, if not found, immediate error |
queryBy… | find the element, if not found, return null |
findBy… | asynchronous search (waits for the element to appear, Promises) |
getAllBy… | expects several elements |
queryAllBy… | does not throw an error if none are found |
The main idea
RTL promotes selectors in the following priority order:
- Role / Text / Label, like a user
- Alt / Title / Placeholder, close to reality
- Test ID, only if there is no other way
If needed, I can give examples of tests using each type of selector.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.