← Back to React Testing Library Mastery
Intermediate18 min read

RTL with Vitest

Configure React Testing Library with Vitest for fast ESM-native test runs.

Why Vitest with RTL

Vitest offers Jest-compatible API with Vite transform pipeline—fast HMR in watch mode and native ESM. Same RTL imports; swap test runner config.

Monorepos using Vite often standardize on Vitest for unit and component tests, Playwright for E2E.

npm install --save-dev vitest jsdom @testing-library/react @testing-library/jest-dom

Vitest Configuration

vitest.config.ts sets environment jsdom, setupFiles, globals optional. Merge Vite resolve aliases so imports match app.

@testing-library/jest-dom/vitest entry extends expect without Jest-specific import side effects.

/// vitest.config.ts
import { defineConfig } from "vitest/config";

export default defineConfig({
  test: {
    environment: "jsdom",
    setupFiles: ["./test/setup.ts"],
    include: ["src/**/*.test.tsx"],
  },
});

Setup File

Import @testing-library/jest-dom/vitest in setup. Configure cleanup afterEach if not automatic. MSW server same as Jest.

Use vi.mock instead of jest.mock; vi.fn instead of jest.fn.

import "@testing-library/jest-dom/vitest";
import { cleanup } from "@testing-library/react";
import { afterEach } from "vitest";

afterEach(() => cleanup());

Migration from Jest

Replace jest with vi in mocks and spies. Timers: vi.useFakeTimers(). Snapshot compatible. Most RTL tests copy unchanged.

Coverage via @vitest/coverage-v8. CI: vitest run --coverage.

  • test.concurrent available for independent async tests
  • pool threads option balances speed and isolation
  • ui mode: vitest --ui for visual test runner
import { describe, test, expect, vi } from "vitest";

vi.mock("./api", () => ({ fetchData: vi.fn() }));

Common Issues

CSS modules: configure Vite css option or identity-obj-proxy equivalent. import.meta.env in tests via vitest define. React 19 and Server Components need experimental test environments—follow RTL and Next.js docs.

Path aliases duplicate from vite.config resolve.alias into vitest config merge.

  • ESM-only packages work smoother in Vitest than Jest ESM mode
  • Use happy-dom alternative to jsdom if lighter sandbox sufficient
  • Document vitest run in CI same as local for consistency

Get In Touch


Ready to discuss your next project? Drop me a message.