[英]How to test useRef with Jest and react-testing-library?
I'm using create-react-app, Jest and react-testing-library for the configuration of the chatbot project.我正在使用 create-react-app、Jest 和 react-testing-library 来配置聊天机器人项目。
I have a functional component that uses useRef hook.我有一个使用 useRef 钩子的功能组件。 When a new message comes useEffect hook is triggered and cause scrolling event by looking a ref's current property.
当一条新消息到来时,会触发 useEffect 钩子并通过查看 ref 的当前属性引起滚动事件。
const ChatBot = () => {
const chatBotMessagesRef = useRef(null)
const chatBotContext = useContext(ChatBotContext)
const { chat, typing } = chatBotContext
useEffect(() => {
if (typeof chatMessagesRef.current.scrollTo !== 'undefined' && chat && chat.length > 0) {
chatBotMessagesRef.current.scrollTo({
top: chatMessagesRef.current.scrollHeight,
behavior: 'smooth'
})
}
// eslint-disable-next-line
}, [chat, typing])
return (
<>
<ChatBotHeader />
<div className='chatbot' ref={chatBotMessagesRef}>
{chat && chat.map((message, index) => {
return <ChatBotBoard answers={message.answers} key={index} currentIndex={index + 1} />
})}
{typing &&
<ServerMessage message='' typing isLiveChat={false} />
}
</div>
</>
)
}
I want to be able to test whether is scrollTo function triggered when a new chat item or typing comes, do you have any ideas?我希望能够测试当新的聊天项目或输入来时是否触发了 scrollTo 功能,您有什么想法吗? I couldn't find a way to test useRef.
我找不到测试 useRef 的方法。
You can move your useEffect
out of your component and pass a ref as a parameter to it.您可以将
useEffect
移出组件并将 ref 作为参数传递给它。 Something like就像是
const useScrollTo = (chatMessagesRef, chat) => {
useEffect(() => {
if (typeof chatMessagesRef.current.scrollTo !== 'undefined' && chat && chat.length > 0) {
chatBotMessagesRef.current.scrollTo({
top: chatMessagesRef.current.scrollHeight,
behavior: 'smooth'
})
}
}, [chat])
}
Now in your component现在在您的组件中
import useScrollTo from '../..'; // whatever is your path
const MyComponent = () => {
const chatBotMessagesRef = useRef(null);
const { chat } = useContext(ChatBotContext);
useScrollTo(chatBotMessagesRef, chat);
// your render..
}
Your useScrollTo test:您的 useScrollTo 测试:
import useScrollTo from '../..'; // whatever is your path
import { renderHook } from '@testing-library/react-hooks'
it('should scroll', () => {
const ref = {
current: {
scrollTo: jest.fn()
}
}
const chat = ['message1', 'message2']
renderHook(() => useScrollTo(ref, chat))
expect(ref.current.scrollTo).toHaveBeenCalledTimes(1)
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.