Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 598
Leo Avatar asked Dec 18 '22 12:12

Leo


1 Answers

I resolved it by:


// import section ...

window.ResizeObserver =
    window.ResizeObserver ||
    jest.fn().mockImplementation(() => ({
        disconnect: jest.fn(),
        observe: jest.fn(),
        unobserve: jest.fn(),
    }));

describe('', () => {
  // test ...
});

like image 83
Leo Avatar answered Mar 04 '23 18:03

Leo