Ir para o conteúdo principal

PorTextoDeRótulo

[Tradução Beta Não Oficial]

Esta página foi traduzida por PageTurner AI (beta). Não é oficialmente endossada pelo projeto. Encontrou um erro? 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

Esta função buscará o rótulo que corresponde ao TextMatch fornecido, e então encontrará o elemento associado a esse rótulo.

O exemplo abaixo encontrará o nó de entrada para as seguintes estruturas 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')

Opções

name

O exemplo acima NÃO encontra o nó de entrada quando o texto do rótulo está fragmentado por elementos. Você pode usar getByRole('textbox', { name: 'Username' }) como alternativa, que é resistente à mudança para aria-label ou aria-labelledby.

selector

Se for importante consultar um elemento específico (ex: um <input>), você pode fornecer um selector nas opções:

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

Observação

getByLabelText não funcionará quando um atributo for em um elemento <label> corresponder a um atributo id em um elemento que não seja de formulário.

// 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>