测试scrollintoview Jest

时间:2018-07-25 20:43:35

标签: reactjs jestjs

我有一个简单的功能:

scrollToSecondPart() {
    this.nextPartRef.current.scrollIntoView({ behavior: "smooth" });
}

,我想使用Jest进行测试。当我调用函数时,出现以下错误:

TypeError: Cannot read property 'scrollIntoView' of null

该代码在应用程序中效果很好,但在单元测试中效果不佳。 这是单元测试:

    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();
});

我想问题是单元测试无法访问this.nextPartRef,但我不知道该如何模拟该元素。 顺便说一句,我正在使用https://reactjs.org/docs/refs-and-the-dom.html中描述的“引用”(我正在使用React.createRef())。

谢谢!

1 个答案:

答案 0 :(得分:5)

所以我偶然发现了这个问题,因为我认为它是关于如何测试Element.scrollIntoView()的,可以通过开玩笑地模拟它来完成,如下所示:

let scrollIntoViewMock = jest.fn();
window.HTMLElement.prototype.scrollIntoView = scrollIntoViewMock;

<execute application code that triggers scrollIntoView>

expect(scrollIntoViewMock).toBeCalled();

但是,这似乎并不是您的目标。在您的测试中,您要在测试中先呼叫scrollToSecondPart(),然后再呼叫expect(scrollToSecondPart).toHaveBeenCalled(),这实际上是在测试scrollToSecondPartLandingPage的功能还是我遗漏了某些东西?