小编Nic*_*ama的帖子

测试scrollintoview Jest

我有一个简单的功能:

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())。

谢谢!

reactjs jestjs

5
推荐指数
1
解决办法
2795
查看次数

标签 统计

jestjs ×1

reactjs ×1