我对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'))
})
我尝试使用模拟函数,但错误仍然存在。
这是 where 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>
我参考了这个 stack overflow 问题的代码:如何在 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
赋值? - Gio Polvara(<HTMLElement>this.messagesEnd).scrollIntoView({ behavior: "smooth" });
- Iskandar Reza