【发布时间】:2018-07-25 20:43:34
【问题描述】:
我有一个简单的函数:
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中描述的“Refs”(我使用的是React.createRef())。
谢谢!
【问题讨论】:
-
模拟元素是一种策略。另一种策略可能是使代码更健壮,例如
if(this.nextPartRef.current){this.nextPartRef.current.scrollIntoView({ behavior: "smooth" });}。您的测试是关于该方法是否已被调用。如果测试是关于滚动是否发生,那么可能需要模拟元素。 -
@Kunukn 感谢您的帮助。您的解决方案正在运行。我理解你的观点,但如果有人可以解释如何模拟这个,那就太好了。是的,我不需要测试卷轴是否发生,但也许有一天我需要:)谢谢!