自从用@testing-library作为react的开始,我就被name
属性弄糊涂了。它可以得到一个渲染按钮的引用,例如:
// <button>Button text</button>
screen.getbyRole("button", {name: /button text/gi})
在这种情况下,name指的是按钮内部的textNode
。输入的情况类似,name
可以指id
、name
或文本内容。
我正在尝试获取一个按钮的引用,该按钮呈现为如下所示:
<button
aria-label="Close"
class="css-1dliicy"
type="button"
>
Create new
<svg>...</svg>
</button>
并且查询时找不到该按钮:
const createNewButton = screen.getByRole('button', {
name: /Create new/gi,
});
型
我显然似乎不知道name
属性是什么意思,但我似乎找不到它的文档。
2条答案
按热度按时间yfjy0ee71#
name
属性引用您试图查询的元素的可访问名称。来自
ByRole
查询文档(第三段):您可以按元素的accessible name查询返回的元素。可访问名称适用于简单情况,例如,等于表单元素的标签、按钮的文本内容或
aria-label
属性的值。如果呈现的内容中存在多个具有相同角色的元素,则可使用该名称查询特定元素。正如@Moistbobo所提到的,由于您的按钮有
aria-label="Close"
,那么Close
将是它的可访问名称。de90aj5v2#
这里的问题是第一个按钮没有一个aria-label,默认情况下将回退到使用按钮内容来实现可访问性。
由于第二个按钮的aria-label为
Close
,因此name
属性在本例中应为Close
。我编写了以下测试来演示这一点。