Search⌘ K
AI Features

Introduction to queries and getBy Variant

Explore the React Testing Library query functions and their getBy variants to locate elements during testing. Understand how getBy returns a single element and how getAllBy handles multiple elements. Discover why getBy raises errors if elements are not found and how these queries work with asynchronous data. This lesson helps you write more precise tests that handle both synchronous and asynchronous rendering scenarios.

The starter project for this lesson contains a PersonPage component that renders a person’s name and scores for a given id. The person’s name and scores are retrieved from an asynchronous function called getPerson. This simulates a function that would retrieve the data from a web service.

A copy of the project is in the code widget below.

export default "test-file-stub";
Simple app to display details on a webpage

Start the app by entering npm start into the terminal. If you are using the code widget, the app will start automatically when the “Run” button is clicked.

The PersonPage component is displayed, which shows a person’s name, email address, and scores.

What is a query?

A query in React Testing Library is a function that finds an element that we want to check in a test. There are different types of queries that find the element in different ways. The query type we have used so far is ByText, which finds the element by its text content. ...