测试图书馆无法找到RC-Menu

发布于 2025-01-17 21:26:06 字数 829 浏览 5 评论 0原文

我正在尝试在使用 Ant 设计的 React 前端上实现集成测试。每当我们创建一个表时,我们都会添加一个操作列,其中有一个 菜单和菜单项执行某些操作。 但是,在使用react-testing-library时,我似乎无法在菜单项中找到正确的按钮。 Ant 设计使用的菜单是 rc-menu,我相信它在渲染组件之外渲染。 阅读测试库文档,我尝试使用 baseElement 和 queryByRole 来获取正确的 DOM 元素,但没有找到任何内容。 这是我正在尝试做的事情的一个例子。这都是异步的,因为表必须在填充之前等待某些数据,仅供参考。

在codesandbox上尝试过

const row = await screen.findByRole('row', {
    name: /test/i
  })

const menu = await within(row).findByRole('menu')
fireEvent.mouseDown(menu)
expect(queryByRole('button', { name: /delete/i })).toBeDisabled()

以删除操作作为菜单项打开菜单

I'm trying to implement integration tests on our React frontend which uses Ant design. Whenever we create a table, we add an action column in which we have a Menu and Menu Items to perform certain actions.
However, I seem unable to find the correct button in the menu item when using react-testing-library. The menu Ant design uses is rc-menu and I believe it renders outside of the rendered component.
Reading the testing-library documentation, I've tried using baseElement and queryByRole to get the correct DOM element, but it doesn't find anything.
Here's an example of what I'm trying to do. It's all async since the table has to wait on certain data before it gets filled in, just an FYI.

Tried it on codesandbox

const row = await screen.findByRole('row', {
    name: /test/i
  })

const menu = await within(row).findByRole('menu')
fireEvent.mouseDown(menu)
expect(queryByRole('button', { name: /delete/i })).toBeDisabled()

the menu being opened with the delete action as menu item

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

燃情 2025-01-24 21:26:06

我在测试 antd + rc-menu 组件时遇到了同样的问题。看起来该问题与延迟弹出窗口渲染有关。这是我如何解决它的一个例子:

    jest.useFakeTimers();
    const { queryByTestId, getByText } = renderMyComponent();
    const nav = await waitFor(() => getByText("My Menu item text"));
    act(() => {
      fireEvent.mouseEnter(nav);
      jest.runAllTimers(); // ! <- this was a trick !
    });
    jest.useRealTimers();
    expect(queryByTestId("submenu-item-test-id")).toBeTruthy();

I had a same issue testing antd + rc-menu component. Looks like the issue is related to delayed popup rendering. Here is an example how I solved it:

    jest.useFakeTimers();
    const { queryByTestId, getByText } = renderMyComponent();
    const nav = await waitFor(() => getByText("My Menu item text"));
    act(() => {
      fireEvent.mouseEnter(nav);
      jest.runAllTimers(); // ! <- this was a trick !
    });
    jest.useRealTimers();
    expect(queryByTestId("submenu-item-test-id")).toBeTruthy();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文