Aller au contenu principal

ByLabelText

[Traduction Bêta Non Officielle]

Cette page a été traduite par PageTurner AI (bêta). Non approuvée officiellement par le projet. Vous avez trouvé une erreur ? Signaler un problème →

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

Cette méthode recherche l'étiquette correspondant au TextMatch donné, puis trouve l'élément associé à cette étiquette.

L'exemple ci-dessous trouvera le nœud d'entrée pour les structures DOM suivantes :

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

Options

name

L'exemple ci-dessus NE trouve PAS le nœud d'entrée lorsque le texte de l'étiquette est fragmenté par des éléments. Vous pouvez plutôt utiliser getByRole('textbox', { name: 'Username' }), qui reste fonctionnel même en cas de basculement vers aria-label ou aria-labelledby.

selector

Si vous devez cibler un élément spécifique (ex: un <input>), vous pouvez fournir un selector dans les options :

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

Note

getByLabelText ne fonctionnera pas si un attribut for dans un élément <label> correspond à un attribut id sur un élément non formulaire.

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