测试scrollintoview Jest [英] Testing scrollintoview Jest

查看:167
本文介绍了测试scrollintoview Jest的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的功能:

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

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

and I would like to test it using Jest. When I call my function I have this error:

TypeError: Cannot read property 'scrollIntoView' of null

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

The code works great in the application but not in the unit test. Here is the unit test:

    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://中描述的"Refs" reactjs.org/docs/refs-and-the-dom.html (我正在使用React.createRef()).

I guess the problem is that the unit test can't access to this.nextPartRef but I don't know how I should mock this element. By the way, I'm using "Refs" has described in https://reactjs.org/docs/refs-and-the-dom.html (I'm using React.createRef()).

谢谢!

推荐答案

所以我偶然发现了这个问题,因为我认为这与如何测试

So I stumbled on this question because I thought it was about how to test Element.scrollIntoView(), which can be done by mocking it with jest as follows:

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

<execute application code that triggers scrollIntoView>

expect(scrollIntoViewMock).toBeCalled();

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

However, that does not seem to be your goal. In your test you are calling scrollToSecondPart() in your test and then expect(scrollToSecondPart).toHaveBeenCalled() which is essentially testing that scrollToSecondPart is a function of LandingPage or am I missing something?

这篇关于测试scrollintoview Jest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆