React Testing Library has methods for several types of queries. There are six query method variants:
getBy*()
- returns the first matching element and throws when an element not found or more than one element found;queryBy*()
- returns the first matching element but doesn’t throw;findBy*()
- returns a promise that resolves with a matching element, or rejects when an element not found after a default timeout or more than one element found;getAllBy*()
,queryAllBy*()
,findAllBy*()
: same as above but return all found elements, not just the first one.
And the queries are:
getByLabelText()
- finds a form element by its ;getByPlaceholderText()
- finds a form element by its placeholder text;getByText()
- finds an element by its text content;getByAltText()
- finds an image by its alt text;getByTitle()
- finds an element by its title attribute;getByDisplayValue()
- finds a form element by its value;getByRole()
- finds an element by its ARIA role;getByTestId()
- finds an element by its test ID.
All queries are available in all variants. For example, besides getByLabelText() there are also queryByLabelText(), getAllByLabelText(), queryAllByLabelText(), findByLabelText() and findAllByLabelText().
Selector | Recommended | Notes |
---|---|---|
button, Button | Never | Worst: too generic |
.btn.btn-large | Never | Bad: coupled to styles |
#main | Never | Bad: avoid IDs in general |
[data-testid="cookButton"] | Sometimes | Okay: not visible to the user, but not an implementation detail, use when better options aren’t available |
[alt="Chuck Norris"], [role="banner"] | Often | Good: still not visible to users, but already part of the app UI |
[children="Cook pizza!"] | Always | Best: visible to the user part of the app UI |
Source: https://blog.sapegin.me/all/react-testing-3-jest-and-react-testing-library/