如何使用 refs 测试 React 组件?
我有一些反应功能组件:
export const Chat = props => {
..............
const messagesRef = useRef(null);
useEffect(() => messages && messagesRef.current.scrollTo(0, 99999), [messages]);
.............
return (
...........
<div className='chat-content__list' ref={messagesRef}>
</div>
............
)
}
我不擅长测试,我只想测试组件的渲染,代码如下:
it('Render Messages chat', async () => {
const { container } = render(<Chat ...someProps />)
}
运行此测试后,我收到此错误: TypeError: messagesRef.current.scrollTo 不是一个函数
如何在测试期间使用 refs 以及如何修复我的情况下的错误?
I have some react functional component:
export const Chat = props => {
..............
const messagesRef = useRef(null);
useEffect(() => messages && messagesRef.current.scrollTo(0, 99999), [messages]);
.............
return (
...........
<div className='chat-content__list' ref={messagesRef}>
</div>
............
)
}
I'm not good at testing and I just want to test the render of my component, the code is like this:
it('Render Messages chat', async () => {
const { container } = render(<Chat ...someProps />)
}
After running this test, I get this error: TypeError: messagesRef.current.scrollTo is not a function
How to work with refs during testing and how to fix the error in my case?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Jest React 测试在名为 jsdom 的浏览器抽象中运行。因为它不是真正的浏览器,所以并未实现所有功能。我怀疑
scrollTo
就是这样的一个例子。例如,此 answer 表明
scrollIntoView
也未实现,要解决它,您可以为其提供一名间谍。Jest 支持为所有测试所需的设置代码提供一个设置文件。您可以考虑将模拟放在那里。
Jest React tests run in an abstraction of the browser called jsdom. Because it isn't a real browser not all functions are implemented. I suspect that the
scrollTo
is one such example.For example, this answer suggests that
scrollIntoView
is also not implemented and to get around it you can provide a spy for it.Jest supports having a setup file for setup code required by all tests. You can look into placing the mock there.