React Testing Library Queries Summary Table

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 Query0
Match
1
Match
>1
Matches
Retry (Async/Await)
Single Element
getBy…Throw errorReturn elementThrow error❌
queryBy…Return nullReturn elementThrow error❌
findBy…Throw errorReturn elementThrow error✅
Multiple Elements
getAllBy…Throw errorReturn arrayReturn array❌
queryAllBy…Return [ ]Return arrayReturn array❌
findAllBy…Throw errorReturn arrayReturn 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.

QuerySpecial UsagePriority to UseExample
getByRole🟢 HighgetByRole(‘button’, {name: /submit/i})
getByLabelTextForm fields🟠 Mediumscreen.getByLabelText(‘Username’)
screen.getByLabelText(‘Password’)
getByPlaceholderTextText input🔴 Low
getByText🟢 Highscreen.getByText(/learn react/i)
getByDisplayValueText input🔴 Lowdocument.getElementById(‘lastName’).value = ‘Norris’
screen.getByDisplayValue(‘Norris’)
getByAltTextImg🔴 Lowscreen.getByAltText(/this image.*? good/i)
getByTitle🔴 Low
getByTestId⚫ Very Low<div data-testid=”custom-element” />
getByTestId(‘custom-element’)
querySelectordocument
(no screen)
⚫ Very Lowdocument.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.

References

https://testing-library.com/docs/queries/about/#priority

Leave a Reply

Your email address will not be published. Required fields are marked *