gpt4 book ai didi

reactjs - 如何在 Jest 和测试/库中测试工具提示标题

转载 作者:行者123 更新时间:2023-12-03 19:41:50 25 4
gpt4 key购买 nike

我想测试工具提示标题是否等于特定文本。
这是我的 antd 工具提示,我想为此编写一个测试:

<Tooltip
title={
this.props.connection ? "Connected" : "Disconnected (Try again)"
}>
<Badge status="default" data-testid="connection-sign" />
</Tooltip>
这是我开玩笑的测试:
 test("Show error title in tooltip", async () => {
baseDom = render(cardComponent);
fireEvent.mouseMove(await baseDom.findByTestId("connection-sign")); //To hover element and show tooltip
expect(
baseDom.getByTitle(
"Disconnected (Try again)"
)
).toBeInTheDocument();
});
但此测试失败,无法找到具有此标题的元素。如何测试我的工具提示是否包含“已断开连接(再试一次)”?

最佳答案

您的测试中有多个错误。

  • 将组件类型而不是组件实例传递给 render
  • baseDom = render(cardComponent); // this is wrong, passing component type
    baseDom = render(<cardComponent />); // this is right, passing component instance created with JSX
  • 使用 mouseMove 而不是 mouseOver 事件
  • 按标题搜索元素并传递文本而不是按文本搜索
  • baseDom.getByTitle("Disconnected (Try again)"); // wrong, because, the prop on the Tooltip is called 'title' but it is actually text as 'getByTitle' looks for HTML title attribute

    baseDom.getByText("Disconnected (Try again)"); // right, because you are actually looking for text not HTML title attribute (but wrong see (4))
  • 使用同步方法进行工具提示搜索而不是异步
  • baseDom.getByText("Disconnected (Try again)");  // wrong, because, Tooltip is added dynamically to the DOM

    await baseDom.findByText("Disconnected (Try again)"); // right
    总而言之,修复了所有错误后,测试应如下所示:
    import React from "react";
    import { render, fireEvent } from "@testing-library/react";
    import App from "./App";

    test("Show error title in tooltip", async () => {
    const baseDom = render(<cardComponent />);

    fireEvent.mouseOver(baseDom.getByTestId("connection-sign"));

    expect(
    await baseDom.findByText("Disconnected (Try again)")
    ).toBeInTheDocument();
    });

    关于reactjs - 如何在 Jest 和测试/库中测试工具提示标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62989500/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com