Skip to main content

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.


These selectors imitate the behavior of users with screen readers and are considered the most correct.

MethodWhat it looks for
getByRoleby the element's role, button, link, heading, etc.
getByLabelTextby the label text on forms
getByPlaceholderTextby the placeholder
getByTextby the visible text
getByDisplayValueby the value of an input field

Example:

js
getByRole("button", { name: /send/i });

2) By alt text and title

Useful for images and icons.

MethodWhat it looks for
getByAltTextby the image's alt
getByTitleby the title attribute

3) By test-id (as a last resort)

Used only when there are no other options.

MethodWhat it looks for
getByTestIdby 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:

PrefixWhat 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:

  1. Role / Text / Label, like a user
  2. Alt / Title / Placeholder, close to reality
  3. 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 ready
Premium

A concise answer to help you respond confidently on this topic during an interview.