Introduction
Suppose we have a lot of elements in our database, and we need to find elements of a particular type. It is difficult to go through all the elements and find the ones we need manually. So do we have any technique that can fetch or find all those elements for use according to our requirements? Yes, we have a technique called “Query”.
The testing library provides queries to find elements on a page. We select different types of queries based on the content. After choosing an element to query, we can use the Events API or user-event to trigger events and simulate the user interactions with the page. The testing library provides us with methods to execute queries. We can also use async APIs to await the changes in DOM(Document Object Model). The testing library provides us with various queries to perform based on the content and the required output. There are two types of queries based on the number of elements we perform queries on; single and multiple elements. Let’s explore the queries ByAltText and ByTitle in this article.
ByAltText
The query ByAltText fetches the elements with specific alt text and returns them. We can use ByAltText as both a single element and multiple elements query. The methods that use ByAltText are
- getByAltText
- queryByAltText
- getAllByAltText
- queryAllByAltText
- findByAltText
- findAllByAltText
Suppose we have an image element with alt text as shown below.
<img alt="three minions" src="/minions.png" />
Let’s learn how to fetch this element using these methods with an example.
import {render, screen} from '@testing-library/react'
render(<MyComponent />)
const result = screen.getByAltText(/three minions/i)
//fetches first element matching with alt text
const result1 = screen.getAllByAltText(/three minions/i) //fetches all the elements with matching alt text
We imported render and screen from the react testing library to fetch and render the component. We performed the queries getByAltText and getAllByAltText using the screen to find the matching alt text elements on the web page. The queries return the image element. The getByAltText returns the first matching element with alt text, whereas the getAllByAltText returns all the elements with matching alt texts.
Note: Observe that we used /…../i in both the methods to fetch the element. This character allows us to ignore the casing and fetches the element with similar alt text irrespective of the case.