javascript - 类型错误 : scrollIntoView is not a function

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

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

})

最佳答案

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

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

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

关于javascript - 类型错误 : scrollIntoView is not a function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53271193/

相关文章:

javascript - jquery mouseleave 排除浏览器垂直滚动条

reactjs - React 我想在 react-chart-2 工具提示中添加文本

javascript - 警告 : Can't call setState (or forceUpdate) on an unmounted component

javascript - 使用 React Router 和 Redux Simple Router 的 onEnter Transitions 不要渲染新路由的组件

javascript - 如何使用 javascript 打开文件/浏览对话框?

javascript - 将对象转换为方括号字符串(不使用 JSON.stringify)

javascript - 环回中的写保护属性

javascript - 在 react route 使用匹配

javascript - 如何将没有值的 props 传递给组件

reactjs - react : difference between <Route exact path ="/"/> and <Route path ="/"/>