类型错误:scrollIntoView 不是函数

IT技术 javascript reactjs react-router jestjs react-testing-library
2021-05-01 20:11:40

我是 react-testing-library / jest 的新手,并试图编写一个测试来查看路线导航(使用 react-router-dom)是否正确执行。到目前为止,我一直在关注有关如何使用自述文件和本教程

我的一个组件在本地函数中使用了 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>

我从这个堆栈溢出问题中引用了代码:How to scroll to bottom in react?

解决方案

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个回答

scrollIntoView未在 jsdom 中实现。这是问题:链接

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

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

如果我们想使用 react 测试库在 react 应用程序中对 'scrollIntoView' 函数进行单元测试,那么我们可以使用 'jest' 来模拟该函数。

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