45

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

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

})
4

2 回答 2

63

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

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

window.HTMLElement.prototype.scrollIntoView = function() {};
于 2018-11-14T07:16:01.970 回答
32

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

window.HTMLElement.prototype.scrollIntoView = jest.fn()
于 2020-02-14T11:27:48.660 回答