ByLabelText

这篇文章详细介绍了如何在测试用例中使用`getByLabelText`方法从DOM中定位具有标签文本的元素,包括HTMLfor关系、aria-labelledby、wrapperlabels和aria-label属性。同时,提到了当标签文本被分割或元素有多重标签时的处理策略和可选参数如selector的使用。
摘要由CSDN通过智能技术生成

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>

  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值