reactjs - 无法测试样式为显示 : none 的元素

标签 reactjs jestjs styled-components react-testing-library

我正在尝试 getByRole我有一个 <li /> ,它是样式组件的子项。

样式组件默认为 display: none ,然后在 min-width 下媒体查询设置为 display: flex .

运行 getByRole('listitem')无需 display: none 即可工作但不是用它,表明styled-components告诉 DOM 因为它被设置为 display: none它不存在。

尽管调试 HTML 输出实际上显示了 <li />正在呈现:

TestingLibraryElementError: Unable to find an accessible element with the role "listitem"

    Here are the accessible roles:

      document:

      Name "":
      <body />

      --------------------------------------------------

    <body>
      <div>
        <div>
          <ul
              class="sc-gzVnrw sc-VigVT kjwzNy"
            >
              <li><!-- bunch of stuff</li>
          </ul>
        </div>
      </div>
    </body>

我曾尝试使用 jest-matchmedia-mock 来模拟媒体查询匹配,没有运气。

我根本不关心测试媒体查询或样式,所以有没有办法告诉样式组件在测试期间不应用样式?

最佳答案

我找到了一种解决方案,它是 dom-testing-library 的一个特性:

getByRole('listitem', { hidden: true })

这包括隐藏元素。

此处有一个详细说明此更改的提交:https://github.com/testing-library/dom-testing-library/pull/352/files/7cdfcfa466774ca78940330fe95d00c9e744b673

关于reactjs - 无法测试样式为显示 : none 的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61877163/

相关文章:

css - 让 Div 仅在页面滚动时出现

javascript - 如何使用 React 的上下文功能将 HTML5 Canvas 上下文传递给 this.props.children?

reactjs - 如何在 Jest 中模拟 window.alert 方法?

reactjs - 使用 Jest 在 React Native 中模拟 Child

reactjs - 如何在 Material UI 的 React 中使用 Typography 作为样式组件

reactjs - 样式化组件 - 使用样式化组件作为另一个组件的基础

javascript - 在数组上创建一些过滤器,然后使用 "All"过滤器取消过滤

reactjs - React js Material-UI 响应式表格

javascript - Jest 比 mocha 慢 40 倍

css - 将 env() css 变量与样式组件一起使用