getByLabelText, queryByLabelText, getAllByLabelText, queryAllByLabelText,
findByLabelText, findAllByLabelText
API# Copy getByLabelText (
container : HTMLElement ,
text : TextMatch ,
options ? : {
selector ? : string = '*' ,
exact ? : boolean = true ,
normalizer ? : NormalizerFn ,
} ) : HTMLElement
This will search for the label that matches the given
TextMatch
, then find the element associated
with that label.
The example below will find the input node for the following DOM structures:
Copy
< label for = "username-input" > Username < / label >
< input id = "username-input" / >
< label id = "username-label" > Username < / label >
< input aria - labelledby = "username-label" / >
< label > Username < input / > < / label >
< label >
< span > Username < / span >
< input / >
< / label >
< input aria - label = "username" / >
Copy import { screen } from '@testing-library/dom'
const inputNode = screen . getByLabelText ( 'Username' )
Options# name
# The example above does NOT find the input node for label text broken up by
elements. You can use getByRole('textbox', { name: 'Username' })
instead which
is robust against switching to aria-label
or aria-labelledby
.
selector
# If it is important that you query an actual <label>
element you can provide a
selector
in the options:
Copy
< label id = "username" > Username < / label >
< input aria - labelledby = "username" / >
< span aria - labelledby = "username" > Please enter your username < / span >
< label >
Username
< input / >
< / label >
< label >
Username
< textarea > < / textarea >
< / label >
Copy const inputNode = screen . getByLabelText ( 'Username' , { selector : 'input' } )
Note
getByLabelText
will not work in the case where a for
attribute on a
<label>
element matches an id
attribute on a non-form element.
Copy
< section id = "photos-section" >
< label for = "photos-section" > Photos < / label >
< / section >