我正在测试scrollIntoVew
事件。有一个探索汽车按钮,当我们点击它时,它会将页面滚动到发现部分。我看到了几个类似的问题,我发现了这个方法:
const scrollIntoViewMock = jest.fn();
Element.prototype.scrollIntoView = scrollIntoViewMock();
这对我挺管用的。单元测试通过。问题是当我删除点击事件时,它也在传递。为什么?为什么?
组件:
"use client";
import Image from "next/image";
import { CustomButton } from "@/components";
const Hero: React.FC = () => {
const handleScroll = () => {
const nextSection = document.getElementById("discover");
if (nextSection) {
nextSection.scrollIntoView({ behavior: "smooth" });
}
};
return (
<div className="hero">
<div className="flex-1 pt-36 padding-x">
<h1 className="hero__title">
Find, book, rent a car—quick and super easy!
</h1>
<p className="hero__subtitle">
Streamline your car rental experience with our effortless booking
process.
</p>
<CustomButton
title="Explore Cars"
containerStyles="bg-primary-blue text-white rounded-full mt-10"
handleClick={handleScroll}
/>
</div>
<div className="hero__image-container">
<div className="hero__image">
<Image src="/hero.png" alt="hero" fill className="object-contain" />
</div>
<div className="hero__image-overlay" />
</div>
</div>
);
};
export default Hero;
单元测试(通过):
it("scrolls to the next section when Explore Cars button is clicked", () => {
render(<Hero />);
const scrollIntoViewMock = jest.fn();
Element.prototype.scrollIntoView = scrollIntoViewMock();
const buttonElement = screen.getByText("Explore Cars");
userEvent.click(buttonElement);
expect(scrollIntoViewMock).toHaveBeenCalled();
});
无点击事件的单元测试(通过):
it("scrolls to the next section when Explore Cars button is clicked", () => {
render(<Hero />);
const scrollIntoViewMock = jest.fn();
Element.prototype.scrollIntoView = scrollIntoViewMock();
expect(scrollIntoViewMock).toHaveBeenCalled();
});
1条答案
按热度按时间9fkzdhlc1#
因为您在测试用例中调用了
scrollIntoViewMock
函数。它应该是:例如
index.test.tsx
:试验结果: