My goal is to mock out the resize-observer-polyfill, in an Angular application when running jest unit tests.
Currently, I get the following error:
TypeError: resize_observer_polyfill_1.default is not a constructor
I found a related issue here, and thus tried to implement a mock next to a component. So this is what I have tried:
_mocks_/resizeObserver.ts
class ResizeObserver {
observe() {
// do nothing
}
unobserve() {
// do nothing
}
}
window.ResizeObserver = ResizeObserver;
export default ResizeObserver;
And then in my spec file import it with:
import ResizeObserver from './_mocks_/resizeObserver';
But that does not solve the problem.
In code, I use the polyfill like this:
import ResizeObserver from 'resize-observer-polyfill';
It's a really frustrating issue, so I really hope to solve the issue in some way.
From that same GitHub Issue:
jest.mock('resize-observer-polyfill', () => ({
__esModule: true,
default: jest.fn().mockImplementation(() => ({
observe: jest.fn(),
unobserve: jest.fn(),
disconnect: jest.fn(),
})),
}));
If you wanted to call the resize handler function immediately, you can add that to the implementation:
jest.mock('resize-observer-polyfill', () => ({
__esModule: true,
default: jest.fn().mockImplementation((cb) => {
// call event handler immediately
cb()
return {
observe: jest.fn(),
unobserve: jest.fn(),
disconnect: jest.fn(),
}
}),
}));
If you wanted to call it on demand, one way you could do it is to add some actual event handlers to the observe function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With