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

Can't test element which is styled to display: none

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

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

运行 getByRole('listitem') 可以在没有 display: none 的情况下工作,但不能与 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