TypeError:scrollIntoView不是函数

Cha*_*wis 9 javascript reactjs jestjs react-router react-testing-library

我是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 | 
Run Code Online (Sandbox Code Playgroud)

这是我的chatbot组件中的功能:

componentDidUpdate() {
    this.scrollToBottom();
}

scrollToBottom = () => {
    this.messagesEnd.scrollIntoView({ behavior: "smooth" });
}
Run Code Online (Sandbox Code Playgroud)

这是测试失败的示例:

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

})
Run Code Online (Sandbox Code Playgroud)

我试图使用模拟功能,但是错误仍然存​​在。

这是分配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>
Run Code Online (Sandbox Code Playgroud)

我从此堆栈溢出问题引用了代码:如何在响应中滚动到底部?

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

})
Run Code Online (Sandbox Code Playgroud)

Kri*_*iti 26

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

window.HTMLElement.prototype.scrollIntoView = jest.fn()
Run Code Online (Sandbox Code Playgroud)

  • 这就像我们在嘲笑scrollIntoView函数。 (3认同)
  • 模拟scrollIntoView的问题在于,虽然我们可以使模拟函数调用另一个函数,但我们永远无法确定滚动是否会在实际情况下触发另一个函数。让我们进行无限滚动,我仍然可以通过测试,并且我的 InfiniteScroller 组件在实际情况下不会触发更多加载。 (3认同)
  • 只是一个观察,正确的做法是不立即调用而使用。因此,请使用不带括号的“jest.fn”,而不是“jest.fn ()”。 (2认同)

Gio*_*Gpx 12

scrollIntoView不在jsdom中实现。问题出在:link

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

window.HTMLElement.prototype.scrollIntoView = function() {};
Run Code Online (Sandbox Code Playgroud)