Introduction
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. The testing library provides us with various queries to perform based on the content and the required output. We can perform queries to fetch a single element or multiple elements. Let’s explore the queries ByText and DisplayValue in this article.
ByText
The query ByText fetches the elements with specific text on the webpage and returns them to the query. We can use ByText as both a single element and multiple elements query. The methods that use ByText are
- getByText
- queryByText
- getAllByText
- queryAllByText
- findByText
- findAllByText
Suppose we have an element with text, as shown below.
<p>Coding Ninjas is the best E-Learning platform with thousands of unique courses</p>
<p>Coding Ninjas</p>
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.getByText(/UNIIQUE/i)
//fetches first element with matching text,ignores cases.
const result1 = screen.getAllByText(/coding ninjas/i)
//fetches all the elements with matching text, ignores cases.
We imported render and screen from the react testing library to fetch and render the component. We performed the queries getByText and getAllByText using the screen to find the matching text elements on the web page. The getByText returns the first matching element with the text “UNIQUE” and ignores the case, whereas the getAllByText returns all the elements with matching text “coding ninjas” without considering the case.