我有一个简单的功能:
scrollToSecondPart() {
this.nextPartRef.current.scrollIntoView({ behavior: "smooth" });
}
Run Code Online (Sandbox Code Playgroud)
我想使用Jest进行测试。当我调用函数时,出现以下错误:
TypeError: Cannot read property 'scrollIntoView' of null
Run Code Online (Sandbox Code Playgroud)
该代码在应用程序中效果很好,但在单元测试中效果不佳。这是单元测试:
it("should scroll to the second block", () => {
const scrollToSecondPart = jest.spyOn(LandingPage.prototype, 'scrollToSecondPart');
const wrapper = shallow(<LandingPage />);
const instance = wrapper.instance();
instance.scrollToSecondPart();
expect(scrollToSecondPart).toHaveBeenCalled();
});
Run Code Online (Sandbox Code Playgroud)
我想问题是单元测试无法访问,this.nextPartRef
但我不知道该如何模拟该元素。顺便说一句,我正在使用https://reactjs.org/docs/refs-and-the-dom.html中描述的“引用” (我正在使用React.createRef()
)。
谢谢!
所以我偶然发现了这个问题,因为我认为它是关于如何测试Element.scrollIntoView()的,可以通过如下方式用笑话来模拟它:
let scrollIntoViewMock = jest.fn();
window.HTMLElement.prototype.scrollIntoView = scrollIntoViewMock;
<execute application code that triggers scrollIntoView>
expect(scrollIntoViewMock).toBeCalled();
Run Code Online (Sandbox Code Playgroud)
但是,这似乎并不是您的目标。在您的测试中,您正在调用scrollToSecondPart()
您的测试,然后expect(scrollToSecondPart).toHaveBeenCalled()
本质上scrollToSecondPart
是哪个功能LandingPage
或我缺少某些功能的测试?
归档时间: |
|
查看次数: |
2795 次 |
最近记录: |