This error occurs because Vitest runs in a Node.js environment that doesn't have browser APIs like ResizeObserver. Your Svelte component (or one of its dependencies) is trying to use ResizeObserver, which isn't available in the test environment.
Here are several ways to fix this:
Option 1: Mock ResizeObserver globally
Add this to your Vitest setup file or at the top of your test files:
// In your vitest.config.js setup file or test file
global.ResizeObserver = class ResizeObserver {
constructor(cb) {
this.cb = cb;
}
observe() {
// Mock implementation
}
unobserve() {
// Mock implementation
}
disconnect() {
// Mock implementation
}
};
Option 2: Use @testing-library/jest-dom polyfills
Install the polyfill package:
npm install -D resize-observer-polyfill
Then add it to your Vitest setup:
// In your vitest.config.js or setup file
import 'resize-observer-polyfill/auto';
Option 3: Configure Vitest with jsdom environment
Make sure your vitest.config.js is set up to use jsdom:
import { defineConfig } from 'vitest/config';
import { svelte } from '@sveltejs/vite-plugin-svelte';
export default defineConfig({
plugins: [svelte({ hot: !process.env.VITEST })],
test: {
environment: 'jsdom',
setupFiles: ['./src/setupTests.js'] // Optional setup file
}
});
Then create src/setupTests.js:
import 'resize-observer-polyfill/auto';
Option 4: Mock it in individual tests
If you only need it for specific tests:
import { beforeEach, vi } from 'vitest';
beforeEach(() => {
global.ResizeObserver = vi.fn().mockImplementation(() => ({
observe: vi.fn(),
unobserve: vi.fn(),
disconnect: vi.fn(),
}));
});
The most common and effective approach is Option 2 or 3, as they provide a proper polyfill that will work across all your tests without needing to mock the functionality.