FakeAlcohol
FakeAlcohol

Reputation: 1010

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!

Upvotes: 15

Views: 8568

Answers (2)

ppavlov
ppavlov

Reputation: 488

It seems that ResizeObserver polyfill is not imported in your testing module.

A proper solution would be to stub the global implementation.

Example Implementation:

global.ResizeObserver = jest.fn(() => ({
    observe: jest.fn(),
    unobserve: jest.fn(),
    disconnect: jest.fn(),
}))

Upvotes: 1

FakeAlcohol
FakeAlcohol

Reputation: 1010

Resolved it by:


// import section ...

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

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

Upvotes: 27

Related Questions