无法使用测试库(React)找到按钮
Cant find button using Test Library (React)
我肯定遗漏了一些很明显的东西,我有一个 React 应用程序,它的左 div 有多个按钮,每个按钮都有不同的文本。我想检查这些按钮中的每一个是否都是 rendered.So 例如找到其中一个按钮(使用测试库)我正在执行以下操作:
screen.getByText("/channels/i", { selector: "button" })
我也试过
screen.getByRole("button", { name: /channels/i })
但我总能得到结果
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
但如您所见,它确实存在
像这样我可能还有 10 个按钮,所以我不明白为什么它说没有可访问的角色。
我做错了什么?
我看到的主要有2种可能。
- 没有等待按钮出现。
如果你的按钮是在某个东西加载完成后呈现的,你需要等待它出现在屏幕上。您可以使用 findBy 查询来做到这一点。
await screen.findByRole('button' { name: 'Channels' });
- 如果您的按钮无法访问——例如被 css 隐藏——它不会被
getByRole
查询找到。您可以通过传递 hidden
道具来验证这一点。请注意,在大多数情况下,您可能不应该使用 hidden
...
screen.getByRole('button' { name: 'Channels', hidden: true });
有用的链接
在这种特殊情况下,这实际上是一个愚蠢的错误,我将我的 render() 放置得有点像这样:
render(<App />)
describe("Navigation", () => {
it("Navigation Test 1", () => {...
所以基本上是因为我在每次迭代之前都在使用测试库,“它”会清理我的 App 组件,使 getByRole 无法找到节点。
当我将 render() 放入“它”中时,一切都开始工作了……愚蠢的错误,使用我提供的代码很难猜到。无论如何谢谢道格。
这也可能是按钮名称错误导致的。例如
screen.getByRole('button', { name: 'Sumbit' })
注意拼写错误:'Sumbit'
而不是 'Submit'
。在这种情况下,您会收到这个非常具有误导性的错误消息:
Unable to find role="button"
我刚刚因为一个简单的错字和错误消息而浪费了半个小时。
我肯定遗漏了一些很明显的东西,我有一个 React 应用程序,它的左 div 有多个按钮,每个按钮都有不同的文本。我想检查这些按钮中的每一个是否都是 rendered.So 例如找到其中一个按钮(使用测试库)我正在执行以下操作:
screen.getByText("/channels/i", { selector: "button" })
我也试过
screen.getByRole("button", { name: /channels/i })
但我总能得到结果
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
但如您所见,它确实存在
像这样我可能还有 10 个按钮,所以我不明白为什么它说没有可访问的角色。
我做错了什么?
我看到的主要有2种可能。
- 没有等待按钮出现。 如果你的按钮是在某个东西加载完成后呈现的,你需要等待它出现在屏幕上。您可以使用 findBy 查询来做到这一点。
await screen.findByRole('button' { name: 'Channels' });
- 如果您的按钮无法访问——例如被 css 隐藏——它不会被
getByRole
查询找到。您可以通过传递hidden
道具来验证这一点。请注意,在大多数情况下,您可能不应该使用hidden
...
screen.getByRole('button' { name: 'Channels', hidden: true });
有用的链接
在这种特殊情况下,这实际上是一个愚蠢的错误,我将我的 render() 放置得有点像这样:
render(<App />)
describe("Navigation", () => {
it("Navigation Test 1", () => {...
所以基本上是因为我在每次迭代之前都在使用测试库,“它”会清理我的 App 组件,使 getByRole 无法找到节点。
当我将 render() 放入“它”中时,一切都开始工作了……愚蠢的错误,使用我提供的代码很难猜到。无论如何谢谢道格。
这也可能是按钮名称错误导致的。例如
screen.getByRole('button', { name: 'Sumbit' })
注意拼写错误:'Sumbit'
而不是 'Submit'
。在这种情况下,您会收到这个非常具有误导性的错误消息:
Unable to find role="button"
我刚刚因为一个简单的错字和错误消息而浪费了半个小时。