Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing scrollintoview Jest

Tags:

reactjs

jestjs

I have a simple function:

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

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

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()).

Thank you!

like image 705
Nicolas Ould Bouamama Avatar asked Jul 25 '18 20:07

Nicolas Ould Bouamama


1 Answers

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

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?

like image 130
David Avatar answered Nov 12 '22 21:11

David