简体   繁体   English

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

[英]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.

相关问题 使用 React-Testing-Library 和 Jest 测试 useRef onError Fn - Test useRef onError Fn, with React-Testing-Library and Jest 如何使用 Jest 和 react-testing-library 测试 react-dropzone? - How to test react-dropzone with Jest and react-testing-library? 如何用 jest 和 react-testing-library 测试 react-toastify - How to test react-toastify with jest and react-testing-library 带有 jest 和 react-testing-library 的测试方法 - test method with jest and react-testing-library 如何使用 Jest 和 React-Testing-Library 模拟和测试 scrollBy? - How to mock and test scrollBy with Jest and React-Testing-Library? 如何使用 react-testing-library 和 jest 测试链接 - How to test link using react-testing-library and jest 如何使用 Jest 和 react-testing-library 测试 Websocket 客户端 - How to test Websocket Client with Jest and react-testing-library 如何在 Typescript 中模拟自定义异步 React 挂钩,包括 useRef() 和 react-testing-library 以访问 result.current - How to mock a custom async React hook including useRef() with jest and react-testing-library to access result.current in Typescript 使用React,Jest,React-Testing-Library测试失败的案例 - Test failing cases with React, Jest, React-Testing-Library 使用 React、Jest、React-Testing-Library 测试失败案例 - Test failing case with React, Jest, React-Testing-Library
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM