跳至主要内容

ByLabelText

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

这将搜索与给定 TextMatch 匹配的标签,然后找到与该标签关联的元素。

以下示例将找到以下 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')

选项

name

上面的示例不会找到标签文本被元素分割的输入节点。您可以改用 getByRole('textbox', { name: 'Username' }),该方法对切换到 aria-labelaria-labelledby 具有鲁棒性。

selector

如果必须查询特定元素(例如 <input>),则可以在选项中提供 selector

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

注意

<label> 元素上的 for 属性与非表单元素上的 id 属性匹配的情况下,getByLabelText 将不起作用。

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