Javascript TypeError:scrollIntoView不是一个函数
我是react测试库/jest的新手,正在尝试编写一个测试,以查看路由导航(使用react路由器dom)是否正确执行。到目前为止,我一直在遵循和这个关于如何使用 我的一个组件在本地函数中使用scrollIntoView,这会导致测试失败Javascript TypeError:scrollIntoView不是一个函数,javascript,reactjs,react-router,jestjs,react-testing-library,Javascript,Reactjs,React Router,Jestjs,React Testing Library,我是react测试库/jest的新手,正在尝试编写一个测试,以查看路由导航(使用react路由器dom)是否正确执行。到目前为止,我一直在遵循和这个关于如何使用 我的一个组件在本地函数中使用scrollIntoView,这会导致测试失败 TypeError: this.messagesEnd.scrollIntoView is not a function 45 | 46 | scrollToBottom = () => { > 47 | this.
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'))
})
测试('
解决方案
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'))
})
test('默认屏幕',()=>{
window.HTMLElement.prototype.scrollIntoView=函数(){};
常量{getByTestId,getByText}=renderWithRouter()
expect(getByTestId('index'))
常量leftClick={按钮:0}
fireEvent.click(getByText('View Chatbot'),左键单击)
expect(getByTestId('chatbot'))
})
scrollIntoView
未在jsdom中实现。问题如下:
您可以通过手动添加它使其工作:
window.HTMLElement.prototype.scrollIntoView = function() {};
如果我们想使用react测试库对react应用程序中的“scrollIntoView”函数进行单元测试,那么我们可以使用“jest”模拟该函数
window.HTMLElement.prototype.scrollIntoView = jest.fn()
你能把this.messagesEnd
的值分配到哪里吗?当然,我更新了原始问题。如果你强制施法,它会起作用吗?(this.messagesEnd).scrollIntoView({behavior:“smooth”})
谢谢@Gpx,这很有效。我已经在原始帖子中添加了解决方案。这就像我们在模仿scrollIntoView函数一样。@Kriti。请解释一下这段代码如何帮助OP在答案中解决他们的问题。请阅读以更好地理解答案是什么。也请浏览该网站,只是一个观察,对吗将在不立即调用的情况下使用。因此,代替jest.fn()
,使用不带括号的jest.fn
。模拟scrollIntoView的问题是,尽管我们可以让模拟函数调用另一个函数,但我们永远无法确定在真实情况下滚动是否会触发另一个函数。让我们看一看无限滚动,我仍然可以通过测试,而我的InfiniteScroller组件确实可以在实际情况下不会触发更多负载。
window.HTMLElement.prototype.scrollIntoView = jest.fn()