【问题标题】:How to find input by span in React-testing-library?如何在 React-testing-library 中按跨度查找输入?
【发布时间】:2021-01-27 21:45:39
【问题描述】:
如何从 span 元素中找到 by text 的复选框?我无法修改我的 HTML。
我希望在输入元素上测试 fireEvent。
`
<label>
<div>
<input type="checkbox" class="checkbox-extra-style">
<span> SPAN A</span>
</div>
</label>
<label>
<div>
<input type="checkbox" class="checkbox-extra-style">
<span> SPAN B</span>
</div>
</label>
`
....
非常感谢您的帮助。
【问题讨论】:
标签:
html
testing
input
react-testing-library
【解决方案1】:
试试const spanText = (await findByText('SPAN A')).parentNode.childNodes;
【解决方案2】:
您应该使用getBy... 查询中提供的额外选项。例如,在这种情况下,screen.getByRole("checkbox", { name: /span a /i })。这将选择
- 页面上按角色排列的复选框
- 将上述内容过滤到与文本“SPAN A”相关联的特定复选框(“SPAN A”将是名称,因为跨度和输入都在同一个标签内)。
如需更多帮助以找到用于某些给定 HTML 的正确查询,testing-library 的testing playground 是一个很好的资源。
【解决方案3】:
Span 没有 aria 角色,因此您有两种选择:
- 修改html添加一个aria-role到span,然后使用screen.getByRole
- 让 HTML 保持原样,并按照 priority list 使用 screen.getByText("SPAN A")