How to mock ResizeObserver to work in unit tests using react testing library
Solution 1:
I chose to add the polyfill as a dev dependency and add the following line to setupTests.js/ts:
global.ResizeObserver = require('resize-observer-polyfill')
Solution 2:
Mock the ResizeObserver:
class ResizeObserver {
observe() {
// do nothing
}
unobserve() {
// do nothing
}
}
window.ResizeObserver = ResizeObserver;
export default ResizeObserver;
sample.test.js
import ResizeObserver from './__mocks__/ResizeObserver';
import module from 'sample;
describe('module', ()=> {
it('returns an instance of ResizeObserver', () => {
// do something that uses the resize observer
// NOTE: The actual observe handler would not be called in jsdom anyway as no resize would be triggered.
// e.g.
expect(module.somethingThatReturnAReference to the resize observer).toBeInstanceOf(ResizeObserver);
});
});
source