While running some Jest tests in React projects, this error can occur: ReferenceError: ResizeObserver is not defined. Usually, it's due to the ResizeObserver not being available in your test environment.
Solution
We need to mock the ResizeObserver.
Create a file in your project's root directory, e.g. setup-jest.js, with the following content.
beforeAll(() => {
global.ResizeObserver = class {
observe() {}
unobserve() {}
disconnect() {}
};
});Add the path to the newly created file to setupFilesAfterEnv in jest.config.js.
setupFilesAfterEnv: ["<rootDir>/setup-jest.js"],Alternatively, you can use a .ts extension for the file if your Jest config is also a .ts file.
