【问题标题】:Testing scrollintoview Jest测试scrollintoview Jest
【发布时间】: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 感谢您的帮助。您的解决方案正在运行。我理解你的观点,但如果有人可以解释如何模拟这个,那就太好了。是的,我不需要测试卷轴是否发生,但也许有一天我需要:)谢谢!

标签: reactjs jestjs


【解决方案1】:

所以我偶然发现了这个问题,因为我认为它是关于如何测试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 的函数还是我遗漏了什么?

【讨论】:

  • 嗨,你是对的,scrollToSecondPart 是来自LandingPage 的函数。在这个函数中我做了一些事情,最后我打电话给scrollInToView。我想测试我的函数scrollToSecondPart,但由于我在原始帖子中显示的错误,单元测试不起作用。看起来你所做的可能会解决我的问题,我会尝试你的解决方案。感谢您的帮助。
  • 嗨@Developer Davo,我已经尝试了你的建议,但它不起作用。我仍然有同样的问题。我想问题是我必须模拟锚的引用,但我不知道该怎么做。无论如何,感谢您的帮助!
  • 非常感谢。
  • @NicolasOuldBouamama 你解决了吗?
  • @Dejan,抱歉回复晚了。我从来没有设法解决这个问题
猜你喜欢
  • 1970-01-01
  • 2018-07-26
  • 2019-05-01
  • 2020-11-24
  • 2018-06-10
  • 2020-12-27
  • 2022-01-06
  • 2020-11-06
  • 2019-03-22
相关资源
最近更新 更多