angularangular-testtestbedangular11

Angular11 test: ReferenceError: ResizeObserver is not defined


I used ResizeObserver in my component and its works fine. But get such error when running ut:

    ReferenceError: ResizeObserver is not defined

      133 |             });
      134 |         
    > 135 |         this.resizeObserver = new ResizeObserver((entries) => {
          |                                   ^
      136 |             const entry = entries.find((e) => e.target === this.wrapper._elementRef.nativeElement);
      137 |             if (entry && entry.contentRect) {
      138 |                 if (this.select && this.select.isOpen) {

I use TestBed to create component:

fixture = TestBed.createComponent(MyComponent);

I can't understand why has this error, I just new an object.

ts version

"rxjs": "~6.5.5",
"tslib": "^2.0.0",
"zone.js": "~0.10.3"

Thanks for your help!


Solution

  • Resolved it by:

    
    // import section ...
    
    window.ResizeObserver =
        window.ResizeObserver ||
        jest.fn().mockImplementation(() => ({
            disconnect: jest.fn(),
            observe: jest.fn(),
            unobserve: jest.fn(),
        }));
    
    describe('', () => {
      // test ...
    });