如何通过Jest和react-testing-library测试useRef?

时间:2019-11-27 08:42:10

标签: reactjs jestjs react-testing-library

我正在使用create-react-app,Jest和react-testing-library来配置chatbot项目。

我有一个使用useRef挂钩的功能组件。当收到新消息时,将触发useEffect挂钩,并通过查看引用的当前属性来引发滚动事件。

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 个答案:

答案 0 :(得分: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)
})