Search code examples
reactjsjestjsenzymereact-testing-libraryref

How to test react component with 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?


Solution

  • 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.