Jest 29 ๐ When to Choose Vitest โ Vite incompatibility, ESM friction, and migration trade-offs
There is a version of this question that gets answered badly on the internet, and it goes like this: Vitest is faster, so migrate. It is faster, in the specific sense that its transform pipeline is incremental and its watch mode uses a real module graph. But speed is never the reason a Jest suite becomes a Vitest suite. The reason is that the application moved to Vite, and now the test runner has to understand a build pipeline the bundler already understands perfectly, and Jest cannot.
That is the whole argument, and it is worth stating as sharply as possible because it is the part that the “it’s faster” framing misses. Vite compiles the source. It resolves import.meta.env.VITE_API into a string literal, expands import.meta.glob('./pages/*.tsx') into a list of dynamic imports, emits a real URL for ?url and a real string for ?raw, and hashes CSS module class names according to a config the application owns. Jest does not do any of that. It runs the file through babel-jest or ts-jest, which produce CommonJS, and then it needs a hand-written moduleNameMapper entry, a transformIgnorePatterns exception, and a mock for every asset type the application imports. Two pipelines, one application, and the second one is maintained by hand and drifts.
The counter-argument matters just as much, and it is the part this chapter will not soften. If the application is not on Vite, Vitest does not inherit a pipeline โ it builds a new one from scratch, and it buys you native ESM execution and a faster watcher in exchange for every edge case Jest fixed across thirty majors. If the application is React Native, Angular, or NestJS, that trade is usually bad. The decision is not about the runner; it is about whether you are already paying for a second pipeline.
This chapter covers the decision in four parts. The first is the Vite incompatibility itself โ the transform, the aliases, the asset types, and the environment variables, with the concrete failures each produces. The second is the ESM friction inside Jest, which is a real cost and a genuinely different one: the flags, the loss of injected globals, and the mock hoisting that jest.unstable_mockModule replaces at a price. The third is the migration itself, mapped key by key, with the parts that translate and the parts that do not. The fourth is the honest accounting of what Jest still wins, so the decision is made on evidence rather than on a benchmark table.
Key point: Vitest’s advantage is not that it is a better test runner โ it is that it is the same runner as the bundler. When the application already runs through Vite, Jest is a second transform pipeline you maintain by hand, and the drift between the two is the bug class that migration eliminates. When the application does not run through Vite, that advantage disappears and the decision becomes a straight trade of maturity for ESM and speed.
Why the decision exists
The two-pipeline problem. A test runner has to do three things to a source file: parse it, transform it, and resolve what it imports. Vite already does all three for the application, using a config the team maintains. Jest does all three again, using a different config that somebody copied, and there is no mechanism that keeps the two in agreement. A new alias added to vite.config.ts silently breaks the test until someone adds a moduleNameMapper entry. An asset type nobody mocked crashes the suite at import time. The drift is unavoidable and it is proportional to how exotic the application’s imports are.
The ESM problem. Jest runs in vm contexts with CommonJS semantics. Native ESM is available behind --experimental-vm-modules, and that flag is the first of six coupled requirements rather than an inconvenience on its own. In ESM mode Jest stops injecting globals, which means every file must import jest, describe, it, and expect from @jest/globals. It stops injecting jest.mock hoisting, which means every mock becomes an await import(). And transformIgnorePatterns becomes an ongoing negotiation with the ecosystem, because more packages ship ESM-only every quarter.
The mocks-hoisting problem. jest.mock works because babel-plugin-jest-hoist rewrites the call to appear above the imports, and that rewrite only makes sense in a CommonJS module. In ESM there is no hoisting step, so jest.unstable_mockModule exists, and it is a different programming model โ the factory is async, the module under test is loaded with a dynamic import(), and a mock declared at the top of the file does not exist when the static imports evaluate. A suite that mocks heavily feels this more than a suite that mocks once.
The maturity problem. Jest has shipped thirty majesties of edge cases: the jsdom gaps that everyone polyfills, the testEnvironmentOptions shape, the snapshot serializer format, the --onlyChanged semantics against a VCS, the retry behaviour of jest-circus, and the hundreds of reports that became behaviour. Vitest is a compatible reimplementation and it is compatible in the way that matters โ expect, describe, test.each, the fake timers, the snapshot format โ but “compatible” is not “identical”, and the differences appear in the corners.
The platform problem. React Native is tested with Jest, officially, with a preset the framework ships. Angular’s mature path is jest-preset-angular; Vitest support exists through Analog and is newer. NestJS generates Jest. None of those are arguments about quality โ they are arguments about who maintains the integration, and a team that picks the non-default runner for a framework owns that integration.
The trade-off. Migration is not free and it is not incremental in the way a version bump is. It is one commit that changes the runner, the config, the mock API, the types, and the snapshot files, and it either works at the end or the branch is abandoned. That makes it a decision to take deliberately, with the suite measured before and after, rather than a decision to take because a blog post had a table with green ticks.
a. The Vite incompatibility โ two pipelines for one application
The failures are specific and each one has a standard Jest workaround, which is exactly the point: the workaround is the second pipeline.
import.meta.env is a compile-time replacement in Vite. Jest’s Babel transform emits CommonJS, and import.meta does not exist in that output, so a source file that reads an environment variable throws at parse time with a message about import.meta being unavailable outside a module.
// src/api/client.ts โ fine under Vite, fatal under a CJS transform
const base = import.meta.env.VITE_API_URL; // replaced at build time
export const get = (p: string) => fetch(`${base}${p}`);
The Jest workaround is a globals entry plus a babel-plugin-transform-import-meta, or a moduleNameMapper that swaps the module for a stub โ and either way the test now reads an environment that no longer comes from .env.
// jest.config.js โ the second pipeline, hand-built
module.exports = {
globals: { 'import.meta': { env: { VITE_API_URL: 'http://localhost:3000' } } },
moduleNameMapper: {
'\\.(css|scss)$': 'identity-obj-proxy', // Vite hashed these; Jest stubs them
'\\.(svg|png)$': '<rootDir>/test/fileMock.js',
},
transformIgnorePatterns: ['/node_modules/(?!some-esm-only-package)/'],
};
import.meta.glob is worse because it is a macro with no runtime equivalent. Vite turns the call into a literal object of dynamic imports at build time. Jest sees a property access on import.meta and has nothing to resolve it to, so the workaround is a per-test mock that enumerates the files by hand โ a list that has to be updated whenever a route is added.
// src/routes/index.ts โ a build-time macro
const pages = import.meta.glob('./pages/*.tsx');
// the Jest workaround is a mock that lists what the bundler would have found
jest.mock('../routes/index', () => ({
pages: {
'./pages/Home.tsx': () => Promise.resolve({ default: Home }),
'./pages/Cart.tsx': () => Promise.resolve({ default: Cart }),
},
}));
CSS modules fail quietly rather than loudly, which makes them the worst case. Vite returns the real, config-hashed class names. identity-obj-proxy returns the key itself, so styles.active evaluates to the string "active" in the test and to something like "_active_1a2b3" in the browser. An assertion on it passes and proves nothing.
// passes under identity-obj-proxy, wrong in the browser
expect(button.className).toBe('active');
Under Vitest none of those three exist as problems, because there is only one config. The test key sits inside the same file the application already uses, so resolve.alias, the React plugin, the CSS setting, and .env all apply to the test by default.
// vitest.config.ts โ the application's pipeline, plus a test section
import { defineConfig } from 'vitest/config';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()], // the same transform as the app
resolve: { alias: { '@': '/src' } }, // the same aliases as the app
test: {
environment: 'jsdom', // install jsdom separately
setupFiles: ['./vitest.setup.ts'],
css: true, // real class names, not a proxy
},
});
b. ESM friction inside Jest โ the six requirements
Native ESM in Jest is a mode, not a setting. Turning it on means satisfying six requirements at once, and any one of them missing produces a SyntaxError or a ReferenceError that names the wrong file.
// package.json โ requirements one and two
{
"type": "module",
"scripts": {
"test": "NODE_OPTIONS=--experimental-vm-modules jest"
}
}
// jest.config.js โ requirements three and four
export default {
transform: {}, // do not emit CJS for ESM files
extensionsToTreatAsEsm: ['.ts'], // or "type": "module" in package.json
};
Requirements five and six are the ones that change how tests are written. The injected globals are gone, so jest and expect must be imported; and jest.mock does not hoist, so a mock is a jest.unstable_mockModule call followed by a dynamic import of the module under test.
// the ESM mock pattern โ async factory, dynamic import, ordered by hand
import { jest, test, expect } from '@jest/globals';
jest.unstable_mockModule('../api/users', () => ({
fetchUser: jest.fn(async () => ({ id: 1, name: 'Alice' })),
}));
// the module must be imported *after* the mock is registered
const { fetchUser } = await import('../api/users');
test('returns the mocked user', async () => {
await expect(fetchUser()).resolves.toMatchObject({ name: 'Alice' });
});
There is a second ESM break that catches people who assume spyOn is safe. A module namespace object has non-configurable properties, so jest.spyOn(mod, 'fn') throws in ESM mode โ and it throws the same way in Vitest, which is why Vitest 3 added vi.mock(path, { spy: true }) to auto-spy every export of a module that it owns the loading of.
// throws in ESM: the namespace is sealed
import * as api from '../api/users';
jest.spyOn(api, 'fetchUser'); // TypeError: not configurable
// Vitest 3 โ mock the module and spy every export in one call
vi.mock('../api/users', { spy: true });
c. The migration itself โ what translates and what does not
The mechanical part is a namespace rename, and it is genuinely mechanical. jest.fn becomes vi.fn, jest.mock becomes vi.mock, jest.spyOn becomes vi.spyOn, jest.useFakeTimers becomes vi.useFakeTimers, and the timers themselves are the same @sinonjs/fake-timers underneath, so advanceTimersByTime and setSystemTime behave identically.
// before โ Jest
const save = jest.fn(async (id: string) => id);
jest.mock('../api/users');
jest.useFakeTimers();
// after โ Vitest
const save = vi.fn(async (id: string) => id);
vi.mock('../api/users');
vi.useFakeTimers();
The API surface is where it stops being a rename. Vitest has helpers Jest does not, and each one replaces a pattern the Jest suite had to write by hand. vi.hoisted solves the hoisting problem for a variable used inside a factory; vi.importActual is the ESM replacement for jest.requireActual; vi.stubEnv and vi.stubGlobal install and restore automatically rather than leaving a mutation behind.
// the variable the factory needs โ hoisted above the mock, like the mock
const mockId = vi.hoisted(() => 'user-1');
vi.mock('../api/users', async (importOriginal) => {
const actual = await importOriginal<typeof import('../api/users')>();
return { ...actual, currentUser: () => mockId };
});
vi.stubEnv('VITE_API_URL', 'http://test'); // restored by unstubAllEnvs
The config translates unevenly, and that is where a migration plan has to be honest. Aliases become resolve.alias and move into the Vite config, which is an improvement because the application and the test now share one map. Environment becomes environment. setupFilesAfterEnv becomes setupFiles. But a regex moduleNameMapper entry has no alias equivalent, and the replacement is to make the asset real โ css: true gives real CSS module names โ or to mock it, which is the same work as before.
// vitest.config.ts โ the keys that translate, and the one that does not
export default defineConfig({
test: {
environment: 'jsdom', // was: testEnvironment
setupFiles: ['./vitest.setup.ts'], // was: setupFilesAfterEnv
globals: true, // keeps the familiar global API
css: true, // no identity-obj-proxy equivalent
},
});
Two things change numbers and both must be expected rather than discovered. The coverage provider defaults differ โ Jest uses Babel instrumentation, Vitest uses v8 unless @vitest/coverage-istanbul is installed โ so the coverage percentage will move on the same source. And the snapshot format is different, so every .snap file is regenerated, which means the diff of the migration commit contains every snapshot in the repository and none of them should be reviewed as a behaviour change.
// vitest.setup.ts โ the matcher package has a Vitest entry point
import '@testing-library/jest-dom/vitest';
// vitest.config.ts โ pin the provider if the numbers must stay comparable
export default defineConfig({
test: { coverage: { provider: 'istanbul', reporter: ['text', 'lcov'] } },
});
d. Where Jest still wins, and where Vitest genuinely does
The honest account starts with the largest item: if the application is not on Vite, the migration buys ESM and a faster watcher and nothing else, and it costs every integration that ships a Jest preset. React Native is the clearest case โ jest-preset is part of the framework’s own toolchain, and there is no first-party Vitest equivalent. Angular’s mature path is jest-preset-angular; the Vitest route is Analog, which is newer and less travelled. A NestJS project generates Jest and documents Jest.
The second item is the reporter and CI surface. Jest’s --onlyChanged, --onlyFailures, --shard, and --listTests are the reference definitions, and the tools that consume them โ jest-junit, the Nx and Turborepo executors, the Bazel rules โ were written against them. Vitest has a built-in junit and json reporter and supports --shard, so the gap is narrower than it once was, but a pipeline built on a Jest-specific reporter is real migration work.
The third is the corner-case behaviour. jest-circus retry semantics, the jsdom environment version pinning, the exact snapshot serializer output, and the --onlyChanged definition against git are all things a large suite has come to depend on implicitly. Vitest’s compatibility is good; it is not a specification.
Where Vitest genuinely wins, and where the wins are not marginal:
# a real browser, not jsdom โ no equivalent first-party option in Jest
npx vitest --browser --browser.name=chromium
// type-level tests, built in โ Jest needs tsd or a separate tsc run
import { expectTypeOf } from 'vitest';
expectTypeOf(save).parameter(0).toEqualTypeOf<string>();
// in-source tests, stripped from the production build by a define
if (import.meta.vitest) {
const { it, expect } = import.meta.vitest;
it('parses', () => expect(parse('a=1')).toEqual({ a: '1' }));
}
Browser mode is the one capability Jest has no answer for at all. jsdom cannot measure a layout, cannot scroll, and cannot paint, which is why every suite carries a set of polyfills for matchMedia, ResizeObserver, and scrollIntoView. A real browser removes the polyfills and the class of assertion that was always about the environment. Type checking in the runner and in-source tests are conveniences rather than categories, but they are conveniences that a Jest suite pays for separately with tsd and a build step.
// vitest.config.ts โ the decision, written down as config
export default defineConfig({
test: {
environment: 'jsdom',
include: ['src/**/*.{test,spec}.{ts,tsx}'],
projects: [ // replaced vitest.workspace.ts
{ test: { name: 'unit', environment: 'node', include: ['src/lib/**'] } },
{ test: { name: 'dom', environment: 'jsdom', include: ['src/ui/**'] } },
],
},
});
Complete Example Session
// ============================================
// PART 1: THE FILE JEST CANNOT PARSE
// ============================================
// src/api/client.ts
// const base = import.meta.env.VITE_API_URL;
// const pages = import.meta.glob('./pages/*.tsx');
// two Vite macros, zero equivalents in a CJS transform
// ============================================
// PART 2: THE SECOND PIPELINE
// ============================================
// jest.config.js โ everything here duplicates vite.config.ts
// module.exports = {
// globals: { 'import.meta': { env: { VITE_API_URL: 'http://localhost' } } },
// moduleNameMapper: { '\\.(css|scss)$': 'identity-obj-proxy' },
// transformIgnorePatterns: ['/node_modules/(?!esm-only-pkg)/'],
// };
// ============================================
// PART 3: THE ESM FLAG
// ============================================
// package.json
// { "type": "module",
// "scripts": { "test": "NODE_OPTIONS=--experimental-vm-modules jest" } }
// ============================================
// PART 4: THE ESM MOCK
// ============================================
import { jest, test, expect } from '@jest/globals';
jest.unstable_mockModule('../api/users', () => ({
fetchUser: jest.fn(async () => ({ id: 1, name: 'Alice' })),
}));
const { fetchUser } = await import('../api/users'); // ordered by hand
test('jest esm mock', async () => {
await expect(fetchUser()).resolves.toMatchObject({ name: 'Alice' });
});
// ============================================
// PART 5: THE SAME TEST IN VITEST
// ============================================
// src/api/users.test.ts
import { describe, it, expect, vi } from 'vitest';
import { fetchUser } from './users';
vi.mock('./users', async (importOriginal) => {
const actual = await importOriginal<typeof import('./users')>();
return { ...actual, fetchUser: vi.fn(async () => ({ id: 1, name: 'Alice' })) };
});
it('vitest mock', async () => {
await expect(fetchUser()).resolves.toMatchObject({ name: 'Alice' });
});
// ============================================
// PART 6: THE CONFIG, REUSING THE APP
// ============================================
// vitest.config.ts
import { defineConfig } from 'vitest/config';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
resolve: { alias: { '@': '/src' } }, // shared with the application
test: {
environment: 'jsdom', // jsdom installed separately
setupFiles: ['./vitest.setup.ts'], // was setupFilesAfterEnv
globals: true, // keeps describe/it/expect global
css: true, // real CSS module names
},
});
// ============================================
// PART 7: THE SETUP FILE
// ============================================
// vitest.setup.ts
import '@testing-library/jest-dom/vitest';
import { afterEach, vi } from 'vitest';
import { cleanup } from '@testing-library/react';
afterEach(() => {
cleanup(); // explicit when globals is false
vi.unstubAllGlobals(); // no Jest equivalent
vi.unstubAllEnvs();
});
// ============================================
// PART 8: THE HOISTED VARIABLE
// ============================================
const id = vi.hoisted(() => 'user-1'); // the factory can see this
vi.mock('./session', () => ({
currentUserId: () => id, // no "mock"-prefix naming rule
}));
// ============================================
// PART 9: THE PROJECTS
// ============================================
// vitest.config.ts โ replaced vitest.workspace.ts in Vitest 3
// projects: [
// { test: { name: 'unit', environment: 'node', include: ['src/lib/**'] } },
// { test: { name: 'dom', environment: 'jsdom', include: ['src/ui/**'] } },
// ]
// ============================================
// PART 10: THE COVERAGE AND THE SNAPSHOTS
// ============================================
// vitest.config.ts
// test: { coverage: { provider: 'istanbul', reporter: ['text', 'lcov'] } }
// $ npx vitest run -u โ regenerate every .snap
// $ npx vitest run --coverage โ compare against the Jest baseline
The ten parts covered the file Jest cannot parse, the second pipeline that resulted, the ESM flag, the ESM mock pattern, the same test written for Vitest, the config that reuses the application’s Vite setup, the setup file with the Vitest entry point for jest-dom, the hoisted variable, the projects form that replaced the workspace file, and the coverage and snapshot regeneration that must be expected rather than reviewed.
Quick Reference
The API rename
| Jest | Vitest |
|---|---|
jest.fn() | vi.fn() |
jest.mock(p, f) | vi.mock(p, f) |
jest.unstable_mockModule | vi.mock(p, f) |
jest.spyOn(o, m) | vi.spyOn(o, m) |
jest.useFakeTimers() | vi.useFakeTimers() |
jest.requireActual(p) | await vi.importActual(p) |
jest.requireMock(p) | await vi.importMock(p) |
jest.mocked(fn) | vi.mocked(fn) |
jest.resetModules() | vi.resetModules() |
The config key mapping
| Jest | Vitest |
|---|---|
testEnvironment | test.environment |
setupFilesAfterEnv | test.setupFiles |
moduleNameMapper | resolve.alias (or test.css) |
transform | Vite plugins |
testPathPatterns | CLI positional filter |
projects | test.projects |
coverageProvider | test.coverage.provider |
globals | test.globals: true |
ESM in the two runners
| Requirement | Jest | Vitest |
|---|---|---|
| Runner flag | --experimental-vm-modules | none |
| Injected globals | Lost in ESM mode | Available with globals: true |
| Mock hoisting | unstable_mockModule + import() | vi.mock hoisted by transform |
spyOn a module | Throws | Throws |
| Namespace spying | Not possible | vi.mock(p, { spy: true }) |
import.meta | Invalid in CJS output | Native |
What Vitest adds
| Feature | Command or API |
|---|---|
| Real browser | vitest --browser |
| Type tests | --typecheck, expectTypeOf |
| In-source tests | import.meta.vitest |
| Env stubbing | vi.stubEnv, vi.unstubAllEnvs |
| Global stubbing | vi.stubGlobal, vi.unstubAllGlobals |
| Hoisted value | vi.hoisted |
Best Practices
โ Do This:
// Decide on the pipeline, not the benchmark
// app on Vite โ strong case, app on Webpack โ weak case // โ
// Share one alias map between the app and the test
resolve: { alias: { '@': '/src' } } // โ
// Keep the familiar global API while migrating
test: { globals: true } // โ
// Pin the coverage provider for a comparable baseline
coverage: { provider: 'istanbul' } // โ
// Use vi.hoisted for values a mock factory needs
const id = vi.hoisted(() => 'user-1'); // โ
// Regenerate snapshots in the migration commit, in one go
// npx vitest run -u // โ
// Keep the Jest config until the branch is green
// both runners installed, both configs present // โ
โ Don’t Do This:
// Migrate because the watch mode is faster
// (that is not the reason; the pipeline is) // โ
// Spy on a module namespace in ESM
import * as api from './api';
vi.spyOn(api, 'get'); // โ
// Assume identity-obj-proxy behaviour carries over
expect(el.className).toBe('active'); // โ
// Review snapshot diffs as behaviour changes
// 400 changed files, all format // โ
// Switch the coverage provider and compare percentages
// 71% โ 68% is the provider, not the code // โ
// Move a React Native or Angular suite off the preset
// jest-preset / jest-preset-angular is the maintained path // โ
// Mock with the Jest factory shape in Vitest ESM
vi.mock('./x', () => ({ y: jest.fn() })); // โ `jest` undefined
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
import.meta parse error | CJS transform output | Move to Vitest, or globals stub |
| Alias works in app, fails in test | Two alias maps | resolve.alias, shared |
| CSS assertion passes wrongly | identity-obj-proxy | test.css: true |
| ESM mock returns nothing | Static import before mock | await import() after vi.mock |
spyOn throws | Sealed namespace | vi.mock(p, { spy: true }) |
| Coverage dropped on migration | Provider changed | Pin istanbul |
| Every snapshot changed | Format differs | Regenerate, do not review |
jest undefined in a Vitest file | Copied factory | vi.fn() |
afterEach not cleaning up | globals: false | Import it, or set globals |
jsdom not found | Installed separately | npm i -D jsdom |
Real-World Examples
1. The Vite macro that cannot be parsed
const base = import.meta.env.VITE_API_URL;
2. The glob macro
const pages = import.meta.glob('./pages/*.tsx');
3. The ESM flag
{ "scripts": { "test": "NODE_OPTIONS=--experimental-vm-modules jest" } }
4. The ESM mock
jest.unstable_mockModule('./x', () => ({ y: jest.fn() }));
const { y } = await import('./x');
5. The Vitest mock
vi.mock('./users', async (importOriginal) => ({ ...(await importOriginal()) }));
6. The hoisted value
const id = vi.hoisted(() => 'user-1');
7. The shared alias
resolve: { alias: { '@': '/src' } }
8. The real CSS
test: { css: true } // class names come from the config
9. The browser
npx vitest --browser --browser.name=chromium
10. The type test
expectTypeOf(save).parameter(0).toEqualTypeOf<string>();
Visual
The two pipelines
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ TWO PIPELINES FOR ONE APPLICATION โ
โ โ
โ the app in Vite โ
โ import.meta.env โโโบ real value โ
โ ?url, ?raw, ?worker โโโบ real URL โ
โ *.module.css โโโบ hashed class names โ
โ โ
โ the same file in Jest โ
โ moduleNameMapper โโโบ a hand-written map โ
โ transformIgnorePatterns โโโบ a list โ
โ identity-obj-proxy โโโบ the key, not the class โ
โ โ
โ two configs, drifting apart โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The ESM tax in Jest
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ THE ESM TAX IN JEST โ
โ โ
โ 1 NODE_OPTIONS=--experimental-vm-modules โ
โ 2 "type": "module" or extensionsToTreatAsEsm โ
โ 3 transform: {} so babel does not emit CJS โ
โ 4 import { jest } from "@jest/globals" โ
โ 5 jest.unstable_mockModule + await import() โ
โ 6 transformIgnorePatterns for every ESM dep โ
โ โ
โ any one missing โโโบ SyntaxError at load โ
โ โ
โ Vitest needs none of this: ESM is native. โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The decision
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ THE DECISION โ
โ โ
โ Is the application already on Vite? โ
โ โ
โ yes โ
โ โโโบ you maintain two pipelines today โ
โ Vitest removes one. Strong case. โ
โ โ
โ no โ
โ โโโบ you gain ESM and speed only โ
โ and lose Jest's depth. Weaker case. โ
โ โ
โ React Native or Angular? Jest, almost always. โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Migration order
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ MIGRATION ORDER โ
โ โ
โ 1 vitest.config.ts with resolve.alias โ
โ 2 environment: jsdom, setupFiles โ
โ 3 globals: true, then delete @types/jest โ
โ 4 replace jest.* with vi.* one file at a time โ
โ 5 fix the mock factories, not the assertions โ
โ 6 regenerate snapshots, then read the diff โ
โ 7 compare coverage numbers, not coverage % โ
โ โ
โ the mocks are the only real work โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Strongest case for Vitest | Application already runs on Vite |
| Weakest case | React Native, Angular, NestJS |
| Jest ESM runner flag | --experimental-vm-modules |
| Jest ESM mock API | jest.unstable_mockModule |
| Vitest mock API | vi.mock with importOriginal |
| Alias mechanism | resolve.alias, shared with the app |
| Setup file key | setupFiles (was setupFilesAfterEnv) |
| CSS modules | test.css: true, real class names |
| Coverage default | Jest babel, Vitest v8 |
| Snapshot format | Different โ regenerate |
| Capability Jest lacks | Real browser mode |
| Capability Jest lacks | In-runner type checking |
Key takeaways:
- The migration reason is the pipeline, not the speed. Vite already transforms, resolves, and expands the application’s imports; Jest does all of it again with a hand-maintained config that cannot stay in sync. A suite on a Vite application is paying for that duplication weekly, and Vitest is the same pipeline as the bundler.
- If the application is not on Vite, the case is much weaker. Vitest then builds a fresh pipeline rather than inheriting one, and the gains reduce to native ESM and a faster watcher โ which are real, but not a reason to give up a preset that the framework maintains for you.
- ESM in Jest is six coupled requirements, not one flag.
--experimental-vm-modules, a module-type declaration, an emptytransform, imported globals,unstable_mockModulewith a dynamic import, and per-packagetransformIgnorePatterns. Any one of them missing fails at load with a message that points somewhere else. spyOnon a module is broken in both runners, for the same reason. A namespace object is sealed, so the property is not configurable. Vitest 3 answers this withvi.mock(path, { spy: true }); Jest has no equivalent and the pattern has to be rewritten as a module mock.- The mechanical rename is the small half.
jest.*tovi.*is a search and replace. The work is in the mock factories โ the async factory, theimportOriginalspread, thevi.hoistedfor anything the factory closes over โ and in the config keys that have no counterpart. - Two things change numbers and must be expected. The coverage provider defaults differ, so the percentage moves on unchanged source; and the snapshot format differs, so every
.snapfile is rewritten. Neither is a behaviour change and neither should be reviewed as one. - Browser mode is the capability Jest has no answer for.
jsdomcannot measure layout, so every suite carries polyfills formatchMedia,ResizeObserver, andscrollIntoView. A real browser removes the polyfills and the assertions that were always about the environment rather than the application.
Remember: The question is not which runner is better in the abstract โ it is whether you are maintaining a second transform pipeline today. If the application runs through Vite, Jest is a hand-built copy of a config that already exists, and every alias, asset type, and environment variable is a place where the copy drifts. That is a strong, concrete, monthly cost with a concrete fix. If the application runs through Webpack, or is a React Native app, or an Angular app on a maintained preset, there is no second pipeline to remove and the migration trades depth for ESM and a faster watcher. Make the call on the pipeline, measure the suite before and after, regenerate the snapshots in one commit, pin the coverage provider so the numbers stay comparable, and leave the mock-heavy files for last because they are the only part of the migration that is genuinely thinking rather than typing.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!