React 测试库 + Material UI DropDown

Fla*_*lva 2 reactjs jestjs material-ui react-testing-library

我遇到一些问题,无法测试 MUI 下拉列表。我收到此错误:Unable to find an accessible element with the role "option" and name "/ninica/i"

\n

我这里有一个示例代码:https://codesandbox.io/s/react-testing-library-material-ui-dropdown-5knbgu

\n

我的测试:

\n
test("select", () => {\n  render(<App />);\n\n  // Get and click in the dropdown\n  const dropdownButton = screen.getByRole("button", { name: /dog name \xe2\x80\x8b/i });\n  fireEvent.click(dropdownButton);\n\n  // Get and click in the dropdown item\n  const dropdownItem = screen.getByRole("option", { name: /ninica/i });\n  fireEvent.click(dropdownItem);\n});\n
Run Code Online (Sandbox Code Playgroud)\n

我已经尝试使用getByTestId但有相同的结果,找不到。

\n

Lui*_*nto 5

首先,对于组件交互,更喜欢使用userEvent如下fireEvent描述的testing-library

\n
\n

内置的 fireEvent 是一个可以轻松调度事件的实用程序。它准确地分派您告诉它的事件,而且只是那些事件 - 即使这些确切的事件从未在浏览器中的实际交互中分派过。

另一方面,user-event 调度事件,就像用户与文档交互时会发生的一样。这可能会导致您之前直接为每个 fireEvent 调度的相同事件,但它也可能捕获使用户无法触发所述事件的错误。这就是为什么您应该使用用户事件来测试与组件的交互。

\n
\n

您可以在此处查看更多相关信息。

\n

与测试未找到角色相关option,it\xc2\xb4s 因为该元素需要一些毫秒才能出现在屏幕上,因此您的测试应该是,async并且您需要使用awaitfindBy查询才能在测试中成功:

\n
import { render, screen, cleanup } from "@testing-library/react";\nimport userEvent from "@testing-library/user-event";\n\ntest("select", async () => {\n  render(<App />);\n\n  const dropdownButton = screen.getByRole("button");\n\n  userEvent.click(dropdownButton);\n\n  const dropdownItem = await screen.findByRole("option", { name: /ninica/i });\n\n  userEvent.click(dropdownItem);\n\n  const typographyEl = await screen.findByText(/Chosen name: ninica/i);\n\n  expect(typographyEl).toBeInTheDocument();\n});\n
Run Code Online (Sandbox Code Playgroud)\n

您可以在这里async/await查看和findBy查询更多信息。

\n

您还可以在此处检查查询的差异。

\n