测试scrollintoview Jest [英] Testing 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()
,这实际上是在测试scrollToSecondPart
是LandingPage
的函数还是我遗漏了某些东西?
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屋!