如何使用 Jest 和 react-testing-library 测试 useRef?

IT技术 reactjs jestjs react-testing-library
2021-05-23 12:23:55

我正在使用 create-react-app、Jest 和 react-testing-library 来配置聊天机器人项目。

我有一个使用 useRef 钩子的功能组件。当一条新消息到来时,会触发 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>
    </>
  )
}

我想测试一下,当有新的聊天项目或者打字来的时候,scrollTo 功能是否被触发,你有什么想法吗?我找不到测试 useRef 的方法。

1个回答

您可以将useEffect组件移出组件并将 ref 作为参数传递给它。就像是

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])
}

现在在您的组件中

import useScrollTo from '../..'; // whatever is your path

const MyComponent = () => {
  const chatBotMessagesRef = useRef(null);
  const { chat } = useContext(ChatBotContext);

  useScrollTo(chatBotMessagesRef, chat);

  // your render..
}

您的 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)
})