TypeError: scrollIntoView is not a function

2020-04-02 07:36发布

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'))

})

2条回答
闹够了就滚
2楼-- · 2020-04-02 08:29

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()
查看更多
看我几分像从前
3楼-- · 2020-04-02 08:35

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() {};
查看更多
登录 后发表回答