I am writing tests using Jest for component which used chart.js to create a line chart. I am getting below error when I am running the tests.
ReferenceError: ResizeObserver is not defined
290 | } 291 | ngAfterViewInit() { > 292 | this.chart = new Chart(this.chartRef.nativeElement, this.chartConfig); | ^ 293 | } 294 | 295 | ngOnInit() { at createResizeObserver (../../../node_modules/chart.js/dist/chart.js:2428:20) at DomPlatform.addEventListener (../../../node_modules/chart.js/dist/chart.js:2502:21) at _add (../../../node_modules/chart.js/dist/chart.js:7051:16) at attached (../../../node_modules/chart.js/dist/chart.js:7070:7) at Chart.bindResponsiveEvents (../../../node_modules/chart.js/dist/chart.js:7079:7) at Chart.bindEvents (../../../node_modules/chart.js/dist/chart.js:7023:12) at Chart._initialize (../../../node_modules/chart.js/dist/chart.js:6547:8) at new Chart (../../../node_modules/chart.js/dist/chart.js:6512:8)
ResizeObserver is being used internally by the chart.js and i am not using explicitly anywhere. Does any one have a solution for this?
Are you using the use-resize-observer
(https://www.npmjs.com/package/use-resize-observer) library or the resize-observer
hook (https://www.npmjs.com/package/@react-hook/resize-observer)?
If your test is failing on a component using use-resize-observer
library, you need to mock the service in your test file (if you're using React):
jest.mock('use-resize-observer', () => ({
__esModule: true,
default: jest.fn().mockImplementation(() => ({
observe: jest.fn(),
unobserve: jest.fn(),
disconnect: jest.fn(),
})),
}));
I see that you use Angular, so this post should be useful: Angular11 test: ReferenceError: ResizeObserver is not defined
window.ResizeObserver =
window.ResizeObserver ||
jest.fn().mockImplementation(() => ({
disconnect: jest.fn(),
observe: jest.fn(),
unobserve: jest.fn(),
}));
describe('', () => {
// test ...
});
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