Zah*_*ebi 6 unit-testing reactjs jestjs react-testing-library
我想测试工具提示标题是否等于特定文本。这是我的 antd 工具提示,我想为此编写一个测试:
<Tooltip
title={
this.props.connection ? "Connected" : "Disconnected (Try again)"
}>
<Badge status="default" data-testid="connection-sign" />
</Tooltip>
Run Code Online (Sandbox Code Playgroud)
这是我开玩笑的测试:
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();
});
Run Code Online (Sandbox Code Playgroud)
但此测试失败,无法找到具有此标题的元素。如何测试我的工具提示是否包含“已断开连接(再试一次)”?
Ros*_*lav 13
您的测试中有多个错误。
renderbaseDom = render(cardComponent); // this is wrong, passing component type
baseDom = render(<cardComponent />); // this is right, passing component instance created with JSX
Run Code Online (Sandbox Code Playgroud)
使用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))
Run Code Online (Sandbox Code Playgroud)
baseDom.getByText("Disconnected (Try again)"); // wrong, because, Tooltip is added dynamically to the DOM
await baseDom.findByText("Disconnected (Try again)"); // right
Run Code Online (Sandbox Code Playgroud)
总而言之,修复了所有错误后,测试应如下所示:
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();
});
Run Code Online (Sandbox Code Playgroud)
小智 5
我尝试了很多方法但没有奏效,因此我尝试使用 鼠标输入而不是 mouseOver 或 mouseMove ,它对我有用。这是测试工具提示内容的解决方案,如下所示:
import { render, cleanup, waitFor, fireEvent, screen } from '@testing-library/react';
// Timeline component should render correctly with tool-tip
test('renders TimeLine component with mouse over(tool-tip)', async () => {
const { getByTestId, getByText, getByRole } = render(
<TimeLine
items={timeLineItems()}
currentItem={currentTimeLineItem()}
onTimeLineItemChange={() => {}}
/>
);
const courseTitle = "Course collection-3";
fireEvent.mouseEnter(getByRole('button'));
await waitFor(() => getByText(courseTitle));
expect(screen.getByText(courseTitle)).toBeInTheDocument();
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8327 次 |
| 最近记录: |