Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
ByLabelText
2.1.
Example
3.
ByPlaceHolderText
3.1.
Example
4.
FAQs
5.
Key Takeaways
Last Updated: Mar 27, 2024

Query ByLabelText and Placeholder Text

Introduction

When making forms we always come across labels and placeholders that specifically tell the user which data is to be filled there. Thus, when testing UI components it would be advised to check them according to the values in the labels and placeholders. This can be done using the testing-library. The testing-library is a family of packages that test the UI component of a given HTML tree structure in a user-centric way. Here, we will learn about the queries ByLabelText and ByPlaceHolderText and how to use them in testing our UI components.

ByLabelText

This query basically searches for a label that matches the given text and finds the element associated with that. Labels are basically texts attached to input fields using the parameter ‘to’ which specifies the input element to which the label is to be attached. Thus clicking on a label of any input field selects the attached input field as well. 

Now we just need to find a node that contains the label text specified that we are finding right now. 

Example

import {screen} from '@testing-library/dom'

const inputNode = screen.getByLabelText('example')

ByPlaceHolderText

This query searches for all elements with a placeholder that matches the given string. Placeholders are an inner parameter of the input fields that take some input as a text. Thus, we can specify a placeholder text which can later be accessed and gives us the input element we are looking for as a node.

Example

import {screen} from '@testing-library/dom'

const inputNode = screen.getByLabelText('example')

FAQs

1. Can we write unit tests using testing-library?

Ans: testing-library can be used to write unit, integration, and end-to-end tests with the library.


2. What is the difference between Enzyme and React testing-library?

Ans: Enzyme is a library that can be used in React as well, thus it is mostly used in conjunction with the testing-library.

 

3. What is the difference between placeholder and label?

Ans: A placeholder is a temporary text filled in input fields that provides hints to the user however a label is a permanent name to any input field.

 

4. What is the return of these queries?

Ans: The return of these queries are DOM nodes that satisfy the queries.

 

Key Takeaways

In this blog, we discussed two queries in the testing library that can be used to test UI components.

You may want to learn more about Angular Testing Library here.

Learning never stops, and to feed your quest to learn and become more skilled, head over to our practice platform Coding Ninjas Studio to practice top problems, attempt mock tests, read interview experiences, and much more.!

Happy Learning!

Live masterclass