如何解决单元测试因找不到元素而失败
这是我第一次进行单元测试,需要一些帮助来理解为什么会出现以下错误。
A)TestingLibraryElementError:无法找到带有文本的元素:访问我的页面。这可能是因为文本被多个元素分解了。在这种情况下,您可以为文本匹配器提供一个功能,以使匹配器更加灵活。
B)期望(接收).toBeInTheDocument()
接收到的值必须是HTMLElement或SVGElement。 收到的值:nulL
c)TestingLibraryElementError:无法通过以下方式找到元素:[data-testid =“ aboutLink”]
这是我在AModal.test.tsx中进行的测试
import React from "react";
import AboutModal from "../../components/AModel";
import { render,screen,fireEvent,getByTestId } from "@testing-library/react";
describe("About Modal",() => {
it("loads",() => {
render(<AboutModal />,{});
// Make sure the pop up has loaded
expect(screen.queryByText("Welcome")).toBeInTheDocument();
});
it("Checks if link works",() => {
// expect(
// screen.queryByText("Visit the About Page for more info")
// ).toBeInTheDocument(); ERROR B is coming here
const { container } = render(<AboutModal />,{});
fireEvent(getByTestId(container,"aboutLink"),new MouseEvent("click")); // Error C is coming here
expect(screen.queryByText("About my document")).toBeInTheDocument();
});
});
这是来自AModel.tsx组件类的代码。
import { Typography,Button,Modal } from "antd";
import React,{ useState,useEffect } from "react";
import styles from "./MyModal.module.scss";
import { RightOutlined } from "@ant-design/icons";
import cookie from "react-cookies";
import Link from "next/link";
const MyModal: React.FC = () => {
const [visible,setVisible] = useState(false);
const { Text } = Typography;
const hide = () => {
setVisible(false);
};
const handleVisibleChange = () => {
setVisible(true);
};
useEffect(() => {
const hasVisitedBefore = cookie.load("hasVisitedBefore");
if (cookie && !hasVisitedBefore) {
setVisible(true);
cookie.save("hasVisitedBefore","true",{});
}
},[]);
const content = () => {
return (
<div className={styles.popupcontainer}>
<div className={styles.popupcontent}>
<p>Learning Jest?</p>
</div>
<div className={styles.footer} data-testid="aboutLink">
<Link href="/about">
<a>
<Text strong>
Visit the About Page for more info <RightOutlined />
</Text>
</a>
</Link>
</div>
</div>
);
};
const popUpTitle = <span className={styles.popuptitle}>Welcome</span>;
return (
<>
<Modal
title={popUpTitle}
centered
mask={false}
className={styles.mystyle}
bodyStyle={{ overflow: "auto" }}
onCancel={hide}
footer={null}
visible={visible}
>
{content()}
</Modal>
</>
);
};
导出默认的MyModal;
对此有任何帮助。.
谢谢
解决方法
请尝试以下操作 -
const {getByTestId} = render(<AboutModal />,{});
fireEvent.click(getByTestId("aboutLink"));
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。