score:6

Accepted answer

I had similar issue using Create React App setup.

If that is your case, you can create a file in your root directory called setupTest.js and add the following code:

  import '@testing-library/jest-dom/extend-expect';
  import 'jest-extended';
    
  jest.mock('./hooks/useResizeObserver', () => () => ({
    __esModule: true,
    default: jest.fn().mockImplementation(() => ({
        observe: jest.fn(),
        unobserve: jest.fn(),
        disconnect: jest.fn(),
    })),
  }));

You can find more information to configure the test environment for Create React App here and the ResizeObserver API here

score:0

Building upon the already excellent answers, here is what I did to get my React Testing library tests running

Take a dependency on the required polyfill in package.json

"devDependencies": {
  ...
  "resize-observer-polyfill": "^1.5.1",
  ...
}

Update the setupTests.ts file as follow.

import * as ResizeObserverModule from 'resize-observer-polyfill';

(global as any).ResizeObserver = ResizeObserverModule.default;

Now your tests should run fine.

score:5

I've added to setupTests.js/ts next code:

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

score:20

Mock the ResizeObserver:

class ResizeObserver {
    observe() {
        // do nothing
    }
    unobserve() {
        // do nothing
    }
    disconnect() {
        // do nothing
    }
}

window.ResizeObserver = ResizeObserver;
export default ResizeObserver;

sample.test.js

import ResizeObserver from './__mocks__/ResizeObserver';
import module from 'sample';

describe('module', ()=> {
     it('returns an instance of ResizeObserver', () => {
           // do something that uses the resize observer
           // NOTE: The actual observe handler would not be called in jsdom anyway as no resize would be triggered.
           // e.g.
           expect(module.somethingThatReturnAReference to the resize observer).toBeInstanceOf(ResizeObserver);
        });
});

source

score:29

I chose to add the polyfill as a dev dependency and add the following line to setupTests.js/ts:

global.ResizeObserver = require('resize-observer-polyfill')

Related Query

More Query from same tag