Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock ResizeObserver polyfill in angular, when doing unit tests with jest?

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.

like image 778
DauleDK Avatar asked Nov 14 '19 19:11

DauleDK


1 Answers

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.

like image 95
bozdoz Avatar answered Apr 28 '23 18:04

bozdoz