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')