使用测试库测试Popover组件的反应

时间:2020-05-29 05:16:25

标签: reactjs react-testing-library

我正在使用一个按钮,将鼠标悬停在该按钮上会显示一个Popover菜单。我正在尝试测试Popover菜单中某些组件的存在,但似乎Popover菜单的呈现方式不正确:

// Displays market menu popover
const marketMenu: JSX.Element = (
  <Menu>
    <Tabs>
      <Tab id={APPLE} title="Apple" />
      <Tab id={ORANGE} title="Orange" />
      <Tab id={BANANA} title="Banana" />
    </Tabs>
  </Menu>
);
return (
  <Popover
    className="market-selector-popover"
    popoverClassName="market-selector-popover"
    content={marketMenu}
  >
    <AnchorButton
      className="market-selector-btn"
      rightIcon="chevron-down"
      text="Fruits"
    />
  </Popover>
);



it("Selects Spot tab and displays it", () => {
    const { container, getByRole } = renderWithProviders(
      <MarketSelector />
    );

    fireEvent.mouseEnter(getByRole("button"));

    const { getByText } = within(
      container.querySelector(".market-selector-popover")
    );
    expect(getByText("Banana")).toBeInTheDocument();
  });

1 个答案:

答案 0 :(得分:0)

回复晚了,但我遇到了类似的问题,我使用 findByText 修复了它。

因此,在您的情况下,我会将代码更改为:

it("Selects Spot tab and displays it", async () => {
    const { container, getByText } = renderWithProviders(
      <MarketSelector />
    );

    // Using the text to select like a user would    
    fireEvent.mouseEnter(getByText("Fruits"));
    expect(await findByText("Banana")).toBeInTheDocument();
  });

使用来自@testing-library/user-event 的 userEventscreen

it("Selects Spot tab and displays it", async () => {
   renderWithProviders(<MarketSelector />); 
   userEvent.hover(screen.getByText("Fruits"));
   expect(await screen.findByText("Banana")).toBeInTheDocument();
});