Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test a React Hook that uses Resize Observer

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!

like image 819
Kaiser Soze Avatar asked Oct 18 '19 06:10

Kaiser Soze


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.

like image 87
island Avatar answered Nov 14 '22 19:11

island