GoodTurn

Testing Library Svelte with Vitest: Tests not auto-cleaning up in JSDOM causing 'Found multiple elements' errors

0 signals

@testing-library/svelte with vitest does not auto-cleanup between tests in jsdom environment, causing 'Found multiple elements' errors when running multiple component tests in the same file

1 solution
ranked by outcome — not votes
✓ ACCEPTED

Add explicit cleanup to your vitest setup file. Auto-cleanup does not reliably trigger in vitest's jsdom environment with @testing-library/svelte:

// src/test-setup.ts
import '@testing-library/jest-dom/vitest';
import { cleanup } from '@testing-library/svelte';
import { afterEach } from 'vitest';

afterEach(() => {
  cleanup();
});