When using React Testing Library, there can be an overwhelming number of query options to choose from. While the flexibility is great, it can also be a headache to select the appropriate query to use for each different test. Here is a collection of query types and their priorities for use. I organized them into two tables for quick and easy lookups.
Types of Queries
Type of Query | 0 Match | 1 Match | >1 Matches | Retry (Async/Await) |
---|---|---|---|---|
Single Element | ||||
getBy… | Throw error | Return element | Throw error | |
queryBy… | Return null | Return element | Throw error | |
findBy… | Throw error | Return element | Throw error | |
Multiple Elements | ||||
getAllBy… | Throw error | Return array | Return array | |
queryAllBy… | Return [ ] | Return array | Return array | |
findAllBy… | Throw error | Return array | Return array |
Priorities and Usage
Some queries are typically the best choice and should be used first, while others should be avoided unless absolutely necessary. Additionally, certain queries are more effective for specific elements.
Query | Special Usage | Priority to Use | Example |
---|---|---|---|
getByRole | 🟢 High | getByRole(‘button’, {name: /submit/i}) | |
getByLabelText | Form fields | 🟠 Medium | screen.getByLabelText(‘Username’) screen.getByLabelText(‘Password’) |
getByPlaceholderText | Text input | 🔴 Low | |
getByText | 🟢 High | screen.getByText(/learn react/i) | |
getByDisplayValue | Text input | 🔴 Low | document.getElementById(‘lastName’).value = ‘Norris’ screen.getByDisplayValue(‘Norris’) |
getByAltText | Img | 🔴 Low | screen.getByAltText(/this image.*? good/i) |
getByTitle | 🔴 Low | ||
getByTestId | ⚫ Very Low | <div data-testid=”custom-element” /> getByTestId(‘custom-element’) | |
querySelector | document (no screen) | ⚫ Very Low | document.querySelector(‘#id’) document.querySelector(‘.class’) |
For complete guide, please visit the link at the bottom of this post.
Playground
If you want to get more familiar with these queries, you can try them out on testing-playground.com. Testing Playground is an interactive sandbox where you can run different queries against your own html, and get visual feedback matching the rules mentioned above.