Search⌘ K
AI Features

Querying Images

Explore how to query images effectively in React Testing Library using ByAltText, ByTitle, and ByRole methods. Understand how to select image elements and verify them in your test cases while enhancing accessibility through proper attributes.

Starter project

The project for this lesson contains a Message component that displays either an error or success message.

A copy of the project is in the code widget below. Click the “Run” button to run the app:

export default "test-file-stub";
App showing message component

Run the app.

We will see that an error message and success message consists of an image followed by some text.

The project contains a half-implemented test to verify the correct image is rendered for an error message. We will fully implement this 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 ByAltText query type

To finish the test implementation, we need to check that the correct img element is within the DOM.

There is a query type called ByAltText, which gets ...