Saltar al contenido principal

ByLabelText

[Traducción Beta No Oficial]

Esta página fue traducida por PageTurner AI (beta). No está respaldada oficialmente por el proyecto. ¿Encontraste un error? Reportar problema →

getByLabelText, queryByLabelText, getAllByLabelText, queryAllByLabelText, findByLabelText, findAllByLabelText

API

getByLabelText(
// If you're using `screen`, then skip the container argument:
container: HTMLElement,
text: TextMatch,
options?: {
selector?: string = '*',
exact?: boolean = true,
normalizer?: NormalizerFn,
}): HTMLElement

Esto buscará la etiqueta que coincida con el TextMatch proporcionado, y luego encontrará el elemento asociado con esa etiqueta.

El siguiente ejemplo encontrará el nodo input para las siguientes estructuras DOM:

// for/htmlFor relationship between label and form element id
<label for="username-input">Username</label>
<input id="username-input" />

// The aria-labelledby attribute with form elements
<label id="username-label">Username</label>
<input aria-labelledby="username-label" />

// Wrapper labels
<label>Username <input /></label>

// Wrapper labels where the label text is in another child element
<label>
<span>Username</span>
<input />
</label>

// aria-label attributes
// Take care because this is not a label that users can see on the page,
// so the purpose of your input must be obvious to visual users.
<input aria-label="Username" />
import {screen} from '@testing-library/dom'

const inputNode = screen.getByLabelText('Username')

Opciones

name

El ejemplo anterior NO encuentra el nodo input cuando el texto de la etiqueta está fragmentado por elementos. En su lugar, puedes usar getByRole('textbox', { name: 'Username' }), que es robusto al cambiar a aria-label o aria-labelledby.

selector

Si es importante consultar un elemento específico (ej. un <input>), puedes proporcionar un selector en las opciones:

// Multiple elements labelled via aria-labelledby
<label id="username">Username</label>
<input aria-labelledby="username" />
<span aria-labelledby="username">Please enter your username</span>

// Multiple labels with the same text
<label>
Username
<input />
</label>
<label>
Username
<textarea></textarea>
</label>
const inputNode = screen.getByLabelText('Username', {selector: 'input'})

Nota

getByLabelText no funcionará cuando un atributo for en un elemento <label> coincida con un atributo id en un elemento que no sea de formulario.

// This case is not valid
// for/htmlFor between label and an element that is not a form element
<section id="photos-section">
<label for="photos-section">Photos</label>
</section>