Test a React Hook that uses Resize Observer

Viewed 2866

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!

1 Answers

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.

Related