使用测试库 (React) 找不到按钮

GB5*_*GB5 4 reactjs create-react-app react-testing-library

我一定遗漏了一些很明显的东西,我有一个反应应用程序,它有一个带有多个按钮的左 div,每个按钮都有不同的文本。我想检查这些按钮中的每一个是否都已呈现。例如,为了找到其中一个按钮(使用测试库),我正在执行以下操作:

screen.getByText("/channels/i", { selector: "button" })
Run Code Online (Sandbox Code Playgroud)

我也试过

screen.getByRole("button", { name: /channels/i })
Run Code Online (Sandbox Code Playgroud)

但我总是得到结果

TestingLibraryElementError: Unable to find an accessible element with the role "button" and name `/channels/i`

    There are no accessible roles. But there might be some inaccessible roles. If you wish to access them, then set the `hidden` option to `true`. Learn more about this here: https://testing-library.com/docs/dom-testing-library/api-queries#byrole
Run Code Online (Sandbox Code Playgroud)

但正如你所看到的,它确实存在

在此处输入图片说明

像那样,我可能还有另外 10 个按钮,所以我不明白为什么它说没有可访问的角色。

我做错了什么?

GB5*_*GB5 6

在这种特殊情况下,这实际上是一个愚蠢的错误,我的 render() 放置得有点像这样:

render(<App />)
describe("Navigation", () => {
        it("Navigation Test 1", () => {...
Run Code Online (Sandbox Code Playgroud)

所以基本上因为我在每次迭代之前使用测试库,“它”会清理我的应用程序组件,使 getByRole 无法找到节点。

当我将 render() 放入“it”中时,一切都开始工作......愚蠢的错误,并且使用我提供的代码,它真的很难猜测。不管怎样,谢谢道格。


Dou*_*oug 5

我看到的主要有两种可能性。

  1. 不等待按钮出现。如果你的按钮是在某个东西加载完成后呈现的,你需要等待它出现在屏幕上。您可以使用findBy查询来做到这一点
await screen.findByRole('button' { name: 'Channels' });
Run Code Online (Sandbox Code Playgroud)
  1. 如果您的按钮以某种方式无法访问 - 例如被 css 隐藏 - 它不会被getByRole查询找到。您可以通过传递hidden道具来验证这一点。请注意,hidden在大多数情况下您可能不应该使用...
screen.getByRole('button' { name: 'Channels', hidden: true });
Run Code Online (Sandbox Code Playgroud)

有用的链接