TypeError: scrollIntoView is not a function

JavascriptReactjsReact RouterJestjsReact Testing-Library

Javascript Problem Overview


I am new to react-testing-library / jest and attempting to write a test to see if the navigation of routes (using react-router-dom) is performed correctly. So far I have been following the README and this tutorial on how to use.

One of my components uses scrollIntoView in a local function and this causes the test to fail.

TypeError: this.messagesEnd.scrollIntoView is not a function

  45 |
  46 |     scrollToBottom = () => {
> 47 |         this.messagesEnd.scrollIntoView({ behavior: "smooth" });
     |                          ^
  48 |     }
  49 |
  50 | 

This is the function in my chatbot component:

componentDidUpdate() {
    this.scrollToBottom();
}

scrollToBottom = () => {
    this.messagesEnd.scrollIntoView({ behavior: "smooth" });
}

And this is a sample of the tests that fail:

test('<App> default screen', () => {

    const { getByTestId, getByText } = renderWithRouter(<App />)

    expect(getByTestId('index'))

    const leftClick = {button: 0}
    fireEvent.click(getByText('View Chatbot'), leftClick) <-- test fails

    expect(getByTestId('chatbot'))

})

I have tried to use a mock function, however the error still remains.

This is where this.messageEnd is assigned:

    <div className="chatbot">
        <div className="chatbot-messages">
            //render messages here
        </div>
        <div className="chatbot-actions" ref={(el) => { this.messagesEnd = el; }}>
            //inputs for message actions here
        </div>
    </div>

I referenced code from this stack overflow question: How to scroll to bottom in react?

SOLUTION

test('<App> default screen', () => {

    window.HTMLElement.prototype.scrollIntoView = function() {};

    const { getByTestId, getByText } = renderWithRouter(<App />)

    expect(getByTestId('index'))

    const leftClick = {button: 0}
    fireEvent.click(getByText('View Chatbot'), leftClick)

    expect(getByTestId('chatbot'))

})

Javascript Solutions


Solution 1 - Javascript

scrollIntoView is not implemented in jsdom. Here's the issue: link.

You might get it working by manually adding it:

window.HTMLElement.prototype.scrollIntoView = function() {};

Solution 2 - Javascript

If we want to unit test 'scrollIntoView' function in a react application using react testing library then we can mock the function using 'jest'.

window.HTMLElement.prototype.scrollIntoView = jest.fn()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCharklewisView Question on Stackoverflow
Solution 1 - JavascriptGiorgio Polvara - GpxView Answer on Stackoverflow
Solution 2 - JavascriptKritiView Answer on Stackoverflow