PorTextoDeRótulo
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" />
- Native
- React
- Angular
- Cypress
import {screen} from '@testing-library/dom'
const inputNode = screen.getByLabelText('Username')
import {render, screen} from '@testing-library/react'
render(<Login />)
const inputNode = screen.getByLabelText('Username')
import {render, screen} from '@testing-library/angular'
await render(Login)
const inputNode = screen.getByLabelText('Username')
cy.findByLabelText('Username').should('exist')
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
getByLabelTextnão funcionará quando um atributoforem um elemento<label>corresponder a um atributoidem 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>