无法在具有特定名称的列表项上使用 getByRole - RTL

reh*_*001 2 testing reactjs jestjs react-testing-library testing-library

如果这是一个重复的问题,我很抱歉。我在其他任何地方都找不到答案。

成分:

<ul>
  <li>Pending tasks</li>
</ul>
Run Code Online (Sandbox Code Playgroud)

测试代码:

expect(getByRole("listitem", { name: "Pending tasks" })).toBeInTheDocument();
Run Code Online (Sandbox Code Playgroud)

错误:

TestingLibraryElementError: Unable to find an accessible element with the role "listitem" and name "Pending tasks"
Run Code Online (Sandbox Code Playgroud)

这是重现此内容的代码和框链接:https ://codesandbox.io/s/wandering-browser-mrf78?file =/ src/App.test.js

即使它显示错误提示无法找到,它仍然建议我将 li 和 ul 标记作为可用角色。

Here are the accessible roles:
 --------------------------------------------------
  list:

  Name "":
  <ul />

  --------------------------------------------------
  listitem:

  Name "":
  <li />

Run Code Online (Sandbox Code Playgroud)

有人可以解释一下我在这里缺少什么吗?我尝试使用正则表达式匹配器,但没有运气。

eps*_*lon 6

Alistitem由作者按规范命名(https://www.w3.org/TR/wai-aria-1.2/#listitem)。

作者姓名定义为

author:名称来自作者在显式标记特性中提供的值,例如 aria-label 属性、aria-labelledby 属性或宿主语言标签机制,例如 HTML 中的 alt 或 title 属性,HTML title 属性具有指定替代文本的最低优先级。

-- https://www.w3.org/TR/wai-aria-1.2/#namecalculation

这并不意味着你应该给它一个 aria-label。如果您发现辅助技术存在问题,您应该只添加 aria 属性。

对于您的具体查询,我建议getAllByRole('listitem').filter(listitem => listitem.textContent === 'Pending task')

  • 由于他正在寻找单个元素,我建议用 find 替换 filter (6认同)