Search⌘ K
AI Features

Querying Form Fields

Explore methods to query form fields in React components with React Testing Library. Understand how to use ByLabelText, ByPlaceholderText, ByDisplayValue, and ByTestId queries to write robust and maintainable tests for input elements. This lesson helps you validate form input values effectively while improving test resilience and accessibility.

Starter project

The starter project contains an EditPersonName component that includes a form that allows a person’s first and last name to be changed.

A copy of the project is in the code widget below. When the “Run” button is clicked, the app is started.

export default "test-file-stub";
Simple app to edit names

Run the app.

We should see a form rendered containing first name and last name fields with a “Save” button. The project also contains a half-implemented test to verify the first name field has the correct initial value. We’ll fully implement the test in this lesson.

The code widget below contains a copy of the project and runs the tests when the “Run” button is clicked:

export default "test-file-stub";
Half implemented test

The ByLabelText query type

To finish the test implementation, we need to get the first name input element and check that its value is "Herman".

There is a query type called ...