9

I created a simple Hook that uses ResizeObserver behind the scenes to run a setState update every time the element is resized.

It works in the browser, but now the problem that I have is that I have no idea how to write tests for it. I tried react-testing-library/hooks but the hook is never called, and I think is because of ResizeObserver.

I tried with Jest, Enzyme, @testing-library but I cannot find a way to really run a test against it.

Basically, in the test, I create a component

function Component {
  const [ref, width] = myHook();

  return (
     <div ref={ref}>{width}</div>
  )
}

Then I set, for example:

window.innerWidth = 400 (I tried to resize and call the hook inside the act function but nothing). At this point the hook will read the ref.current.width and return the width value

I expect value to change on resize, but it does not. However this exact component, when used in the browser works fine. How can I make sure that ResizeObserver is called? I also imported the polyfill but nothing. Mocking ResizeObserver will make it impossible for me to test the hook and I cannot call the hook outside a React Function! Any help is appreciated, thanks!

Kaiser Soze
  • 1,362
  • 3
  • 14
  • 31
  • I reached this question while searching for a way to mock ResizeObserver for unit tests. Here is my answer in another related question: https://stackoverflow.com/a/76220429/2528232 – Valery May 10 '23 at 15:55

1 Answers1

3

react-testing-library uses jsdom under the hood to simulate the DOM and it deliberately doesn't implement layout code like the ResizeObserver you want to test. Aside from switching to a testing library like cypress that runs tests in a real browser, you can create a fake MockResizeObserver and implement the layout behavior yourself.

You can then use jest.spyOn to replace ResizeObserver with MockResizeObserver for your tests.

island
  • 43
  • 5