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')
Options
name
上面的例子没有找到由元素分隔的标签文本的输入节点。你可以使用 getByRole('textbox', { name: 'Username' }) 代替,它对于切换到 aria-label 或 aria-labelledby 是很稳健的。
selector
如果您查询的是特定元素(例如 <input>),则可以在选项中提供一个选择器:
// 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>