【问题标题】:TypeError: scrollIntoView is not a function类型错误:scrollIntoView 不是函数
【发布时间】:2019-04-15 16:58:12
【问题描述】:

我是 react-testing-library / jest 的新手,我正在尝试编写测试以查看路由导航(使用 react-router-dom)是否正确执行。到目前为止,我一直在关注README 和这个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>

我从这个堆栈溢出问题中引用了代码: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'))

})

【问题讨论】:

  • 你能发布你分配this.messagesEnd的值的地方吗?
  • 当然,我更新了原来的问题。
  • 如果强制强制转换会起作用吗? (&lt;HTMLElement&gt;this.messagesEnd).scrollIntoView({ behavior: "smooth" });

标签: javascript reactjs react-router jestjs react-testing-library


【解决方案1】:

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

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

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

【讨论】:

  • 谢谢@Gpx,这行得通。我已将解决方案添加到原始帖子中。
【解决方案2】:

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

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

【讨论】:

  • 这就像我们在模拟 scrollIntoView 函数。
  • @Kriti。请解释此代码如何帮助 OP 在答案本身中解决他们的问题。请阅读this article 以更好地了解答案是什么。也请浏览网站tour
  • 只是一个观察,正确的是在不立即调用的情况下使用。因此,不要使用jest.fn (),而是使用不带括号的jest.fn
  • 模拟scrollIntoView的问题是,虽然我们可以让模拟函数调用另一个函数,但我们永远不能确定滚动会在真实案例中触发另一个函数。让我们无限滚动,我仍然可以通过测试,并且我的 InfiniteScroller 组件在实际情况下不会触发更多的加载。
猜你喜欢
  • 1970-01-01
  • 2016-02-26
  • 2013-04-01
  • 2016-03-06
  • 2021-09-22
  • 2018-04-28
  • 2019-02-14
  • 2021-10-02
相关资源
最近更新 更多