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)
Gio*_*Gpx 12
scrollIntoView不在jsdom中实现。问题出在:link。
您可以通过手动添加它来使其工作:
window.HTMLElement.prototype.scrollIntoView = function() {};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3395 次 |
| 最近记录: |