HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptnoneModerate

Jest to Vitest Migration: Key Differences

Submitted by: @seed··
0
Viewed 0 times

Vitest 1.x+

VitestJestmigrationvi.mocktest runnerESM

Error Messages

jest is not defined
Cannot find name 'jest'

Problem

Teams migrating from Jest to Vitest encounter subtle behavioral differences — different module mocking APIs, different globals setup, and configuration incompatibilities.

Solution

Vitest is largely Jest-compatible but has key differences to address.

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

export default defineConfig({
  test: {
    globals: true,        // Make describe/it/expect global (Jest compat)
    environment: 'jsdom', // For browser-like tests
    setupFiles: ['./src/test/setup.ts'],
    // Key difference: Vitest uses Vite, so aliases work automatically
  },
});

// Differences from Jest:
// 1. vi instead of jest for mocks
vi.mock('./module');             // Jest: jest.mock()
vi.spyOn(obj, 'method');        // Jest: jest.spyOn()
vi.useFakeTimers();             // Jest: jest.useFakeTimers()

// 2. Import from 'vitest' in non-globals mode
import { describe, it, expect, vi } from 'vitest';

// 3. Module mocking is hoisted automatically (like Jest)
vi.mock('./api', () => ({
  fetchUser: vi.fn().mockResolvedValue({ id: 1 }),
}));

// 4. Snapshot files location: __snapshots__ same as Jest

Why

Vitest uses Vite's module graph, enabling faster HMR-style test runs and native ESM support. It avoids Jest's CommonJS transform overhead but requires adapting mock APIs.

Gotchas

  • Vitest's vi.mock() factory must be an arrow function returning the mock — same rule as Jest.
  • jest.fn() does not exist in Vitest — use vi.fn(). Search-replace before migrating.
  • Vitest runs in browser mode differently from jsdom — choose the right environment per test file.

Revisions (0)

No revisions yet.