TypeError: scrollIntoView is not a function

TypeError: scrollIntoView is not a function

我是 react-testing-library / jest 的新手,正在尝试编写测试以查看路由导航(使用 react-router-dom)是否正确执行。到目前为止,我一直在关注 README and this tutorial 如何使用。

我的一个组件在本地函数中使用了 scrollIntoView,这导致测试失败。

TypeError: this.messagesEnd.scrollIntoView is not a function

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

这是我的聊天机器人组件中的功能:

componentDidUpdate() {
    this.scrollToBottom();
}

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

这是失败测试的示例:

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

})

我尝试使用模拟函数,但错误仍然存​​在。

这是 this.messageEnd 的分配位置:

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

我引用了这个堆栈溢出问题的代码:

解决方案

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

})

scrollIntoView在jsdom中没有实现。这是问题所在:link.

您可以通过手动添加它来使其工作:

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

如果我们想使用 React 测试库对 React 应用程序中的 'scrollIntoView' 函数进行单元测试,那么我们可以使用 'jest'.

模拟该函数
window.HTMLElement.prototype.scrollIntoView = jest.fn()