use-resize-observer: "ResizeObserver is not defined" error when running Jest
Hello đ
Using useResizeObserver
crashes my appâs tests. Jest uses JSDom, which apparently doesnât support the ResizeObserver API.
I know we can detect when Jest is running, but React doesnât support conditionally calling hooks, so I donât know how to prevent Jest from crashing. I think the fix has to be done inside the hook.
About this issue
- Original URL
- State: closed
- Created 4 years ago
- Comments: 21 (4 by maintainers)
adding this line of code in the testing file fixed the error for me global.ResizeObserver = require(âresize-observer-polyfillâ)
I managed to bypass the issue like that.
Solution for vitest write in the file with the test at the highest level of nesting
In case it helps someone, I found that you can mock module to use
polyfilled
when in tests with a few lines. This will at least get around theundefined
error. It wonât add any functionality tho.I work on a component library where we use the hook to enhance component functionality behind a prop. So if
hasResize=false
, we donât use the values provided from the hook. The library does not provide a polyfill for the same reasons you list in the readme.The hook canât be placed behind a browser support conditional - so even when
hasResize=false
is false, the hook throws an error in environments where RO is not supported. This effectively requires our consumers to provide an RO polyfill when they may not even have configured props to use the hook.The only solution for us is to have two components, Component and ComponentWithResize. Render one or the other depending on prop and support.
A check for RO support in the hook would be very inexpensive and fix these issues.
global.ResizeObserver = class { observe() {} unobserve() {} disconnect() {} }; This code solved my issue
For those looking for a more configurable solution, the below worked for me:
jest.config.js
Hi, I was getting âplease install a polyfill for ResizeObserverâ after migrating jest26 to jest28 version in angular application. We are not using ResizeObserver in our application but I am not sure whether any dependency with NGXCHARTS, So I was getting this error suddenly.
I have tried above solution of bypassing, it worked thank you.
class ResizeObserver { observe() {} unobserve() {} disconnect() {} }
describe(âComponentâ, () => { window.ResizeObserver = ResizeObserver; })
I used polyfilled version,
import useResizeObserver from "use-resize-observer/polyfilled";
because of issues in IOs 12. Maybe this will help.I added a test to #42, it should be ready to go.