【问题标题】: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 })。这将选择

      1. 页面上按角色排列的复选框
      2. 将上述内容过滤到与文本“SPAN A”相关联的特定复选框(“SPAN A”将是名称,因为跨度和输入都在同一个标​​签内)。

      如需更多帮助以找到用于某些给定 HTML 的正确查询,testing-librarytesting playground 是一个很好的资源。

      【讨论】:

        【解决方案3】:

        Span 没有 aria 角色,因此您有两种选择:

        1. 修改html添加一个aria-role到span,然后使用screen.getByRole
        2. 让 HTML 保持原样,并按照 priority list 使用 screen.getByText("SPAN A")

        【讨论】:

        • 感谢博尔哈的提示!
        猜你喜欢
        • 2019-03-30
        • 2019-10-28
        • 2021-04-10
        • 2022-08-06
        • 2019-08-06
        • 2020-10-17
        • 1970-01-01
        • 1970-01-01
        • 2021-06-02
        相关资源
        最近更新 更多