Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Queries
3.
Types of Queries
3.1.
Single Element
3.2.
Multiple Elements
4.
Debugging
5.
FAQs
6.
Key Takeaways
Last Updated: Mar 27, 2024
Easy

Introduction to Queries

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”. Let’s explore what a query is and how to execute it in this article.

Queries

Queries are provided by the testing library to find elements on a page. We select different types of queries based on the content. After selecting 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). Let’s learn how to execute a query now.

import {render, screen} from '@testing-library/react' 

test('should show login form', () => {
 render(<Login />)
 const input = screen.getByLabelText('Username')
 })


We imported render and screen from the react testing library in the above code. The above query is used to find an element in the login page with the label Username, using the screen to find the element on that page and the render() method to render the login page if any changes are done.

Types of Queries

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. 

Single Element

These queries return a single element and throw an error or return NULL if we find elements more or less than one.

Single Element Description
getBy Returns the matching node and throws an error if there are elements more or less than one.
queryBy Returns the matching node and throws an error if more than an element is found. Returns null if there are no matching elements.
findBy Returns a promise that resolves on finding an element. The promise is rejected if elements found are more than one or less than one.

Multiple Elements

These queries return an array of elements and throw an error or return an empty array if we find elements less than one.

Multiple Elements Description
getAllBy Returns an array of matching nodes and throws an error if there no elements are found.
queryAllBy Returns an array of matching nodes and returns null if there are no matching elements.
findAllBy Returns a promise that resolves on finding an array of elements. The promise will be rejected if no elements are found.

Let’s create an HTML page with basic div elements for an input field and text to perform queries on them.

<body>
 <div id="element">
   <label for="email">Username</label>
   <input id="email" />
   <p>Coding Ninjas</p>
 </div>
</body>


Let’s learn how to execute the queries for the HTML page above.

import {screen, getByLabelText, getByText} from '@testing-library/react' 

// Using screen
const input1 = screen.getByLabelText('Username') 

// without using screen
const container = document.querySelector('#element')
const input2 = getByLabelText(container, 'Username')
const input3 = screen.getByText('Coding Ninjas');


We imported the methods getByLabelText and getByText in the above code along with the screen. The getByLabelText finds the element with the label Username and returns it. The getByText method finds the text that matches ‘Coding Ninjas’  and returns it. If we do not want to use the screen, we can provide a container and use it to find the matching elements.

Debugging

The queries can be debugged using the screen.debug() method along with the queries. This is similar to the method console.log() we use in scripting languages.  

import {screen} from '@testing-library/dom'
document.body.innerHTML = `<button>test</button>
    <span>multi-test</span>
    <div>multi-test</div>`

// debug document
screen.debug()
// debug single element
screen.debug(screen.getByText('test'))
// debug multiple elements
screen.debug(screen.getAllByText('multi-test'))


We are debugging a single element, multiple elements, and the entire document using the screen.debug() in the above code. The query is given inside the debug method to perform debugging on them. They allow you to see the output of HTML elements we perform queries on as we build the tests.

FAQs

  1. What is a query?
    The Queries are provided by the testing library to find elements on a page. We select different types of queries based on the content.
     
  2. What is a screen in the testing library?
    A screen is an object from React Testing Library that provides methods for querying, debugging, and rendering the elements of an HTML page.
     
  3. What is debugging?
    The debugging lets you see the output of HTML elements we perform queries on as we build the tests. The queries can be debugged using the screen.debug() method along with the queries.
     
  4. What are the primary query methods?
    The primary query methods we use are getBy, queryBy, and findBy. The necessary elements can be queried by adding the extension to these methods like getByText, findByLabelText, etc.
     
  5. How do I find the matching text on a page?
    The matching text on a page can be found using the method screen.getByText(). This method finds a matching text on the page and returns it. We can use getAllText() to find an array of matching texts.

Key Takeaways

We discussed queries, their types, and how to execute queries based on the content and required output. We also learned debugging in this article. Now you can perform basic queries and debug on any page. 

Hey Ninjas! We hope this blog helped you enhance your knowledge of queries. If you want to learn more, check out Coding Ninjas for more unique courses and guided paths. Also, try Coding Ninjas Studio for more exciting articles, interview experiences, and fantastic Data Structures and Algorithms problems. Do upvote our blog to help the other ninjas grow.

Happy Coding!

Live masterclass