@testing-library getByRole不返回CSS隐藏的元素

btxsgosb  于 2023-06-25  发布在  其他
关注(0)|答案(2)|浏览(123)

这可能是预期的行为,但我想确保,如果是这样的话,找到一种替代方法。
假设有一个react元素
<span role="presentation" className="ag-hidden">
其中ag-hidden在样式表中定义为.ag-hidden { visibility: hidden; }display: none
样式表被注入到DOM中。

  • screen.getAllByRole("presentation")不返回元素。
  • 如果样式表从DOM中删除,则会找到该元素。
  • 通过test id找到类似的隐藏元素,如下所示:

<span data-test="el" className="ag-hidden">
我想使用以下方法,但它的工作原理很奇怪:

const selector = ".ag-hidden"l
const hiddenByRoleAndSelector = screen.queryByRole("presentation", {
  name: (_: string, el: Element) => {
    // the required element gets here, and it matches the selector
    console.log("n", el.matches(selector), el);
    // so we return true for it
    return el.matches(selector);
  }
});

// ...but eventually get null

那么,我应该如何测试被样式隐藏的元素呢?(不要总是求助于test-id或可本地化的标签、文本等)
Here is the codesandbox demo

s4n0splo

s4n0splo1#

RTL的关键在于它测试用户在屏幕上看到的内容。但我明白,当你需要测试一个非常具体的元素时,有时会令人沮丧。
您有一个underlying jest jsdom选择器形式的退出窗口。您可以像在浏览器中一样使用querySelector来查找特定的类,例如ag-hidden。或者可以使用data-test-id,如前面所示。

dgjrabp2

dgjrabp22#

queryByRole包含隐藏属性,如果您查询它:

const hiddenDiv = screen.queryByRole('presentation', { hidden: true });

相关问题