| | |

Vitest 36 🧪 Migrating from Jest — Globals, mockReset semantics, and module factories

⏱️ Estimated read: 25 min | |

Most Jest suites migrate to Vitest in an afternoon and then spend a week fixing three files. The bulk of the change is mechanical — jest.fn() becomes vi.fn(), jest.mock() becomes vi.mock(), the config object moves from jest.config.js into a test: key — and a find-and-replace gets ninety percent of it. The remaining ten percent is where the migration actually lives, and it is concentrated in three places: how globals are exposed, what mockReset means, and how a module factory is hoisted above the imports that use it.

Those three are not accidents of implementation. Jest runs tests through Babel or ts-jest and a CommonJS module registry it controls; Vitest runs them through Vite’s ESM pipeline with its own module runner. The mocking surface looks the same because it was designed to, but the semantics underneath were rebuilt, and the points where a rebuild cannot be a copy are exactly the points that break on migration.

This chapter covers the three. It walks through globals: true and why the migration guide recommends turning it off again, the three-level mock lifecycle and the one documented behaviour where Vitest deliberately diverges from Jest, and the module factory in all its forms — plain, hoisted, partial, and the { spy: true } shorthand. It ends with the config file mapping, because the config is where the mocking flags and the setup files are decided.

Key point: vi.mock factories are hoisted above the imports by Vite’s transform, mockReset on a vi.fn(impl) restores impl rather than emptying the mock, and globals: true exists only as a migration aid — the three differences are deliberate, and each has a one-line fix that should be applied during migration rather than after the first confusing failure.


Why migration needs care beyond find-and-replace

The module system changed underneath. Jest loads test files through a custom CommonJS registry and a transformer it owns, which lets it intercept require and swap a module for a mock at any point. Vitest runs files through Vite as ESM and uses a module runner that executes them in a Node worker. The intercepting is done by a source transform that rewrites vi.mock(...) into a registration call placed before the imports. The API survived the change; the mechanism did not, and any reliance on the mechanism — a factory closing over a top-level variable, a mock installed mid-file — breaks.

The naming is similar on purpose. describe, test, expect, beforeEach are the same words, which is why the migration feels trivial and also why the failures are surprising. A test that reads identically runs identically in ninety-nine cases, and the hundredth is the one where the difference matters. Reading the diff as “same test, different runner” is the single most common cause of a two-day migration where an afternoon was planned.

mockReset was rebuilt, not ported. The three-function lifecycle — clear, reset, restore — looks identical, and two of the three behave identically. The third, mockReset, diverges in a way that is documented and deliberate: Vitest restores the original implementation passed to vi.fn(impl), while Jest removes the implementation entirely. A test that relied on “reset means the mock now returns undefined” will, after migration, call the real code path instead. That is not a subtle difference; it is a difference between a stub and a live call.

Hoisting has no naming convention in Vitest. Jest’s Babel plugin allows a factory to reference outer variables if their names begin with mock — a convention baked into the transformer. Vitest has no such convention, because the transform does not parse identifiers. Instead there is an explicit escape hatch, vi.hoisted, which moves a value into the same hoisted position the factory occupies. A migrated factory that reads mockUser will throw a temporal-dead-zone ReferenceError the first time it runs, and the error message points at the factory line rather than at the convention that was silently dropped.

The async gap is real. jest.requireActual and jest.requireMock are synchronous, because Jest’s registry is synchronous. Their Vitest counterparts, vi.importActual and vi.importMock, return promises, because an ESM module graph is asynchronous by nature. A factory that must return the real module’s exports plus one overridden function becomes an async factory. Every call site that copied requireActual into a factory has to become await, and the factory has to be async.

The config file is a different config file. Jest’s config has moduleNameMapper, transform, setupFilesAfterEnv, testMatch, and transformIgnorePatterns. Vitest has resolve.alias, Vite plugins, setupFiles, include, and server.deps.inline. The names differ because the underlying systems differ — Vitest’s resolution is Vite’s resolution, and its transform is Vite’s transform. A migration that keeps moduleNameMapper in a test: block does nothing, silently, and the imports it was meant to map fail with a plain module-not-found.

The trade-off is worth accepting once. Vitest is not a Jest clone and does not try to be. The areas where it diverges are the areas where it gained something: ESM-native mocking, in-source testing, browser mode, the Standard Schema matcher, the { spy: true } mock shorthand. Migrating means giving up the habit of assuming identical semantics and accepting the documented differences, and the three in this chapter are the ones that cost the most if they are discovered by accident rather than read about first.


a. Globals and the jest → vi rename

Jest exposes describe, test, expect, jest, and the lifecycle hooks as ambient globals. Nothing is imported, and the TypeScript types come from @types/jest. Vitest defaults to the opposite: every one of those is an export of the vitest package, and the ambient globals are opt-in.

// vitest.config.ts — turn the Jest-style globals back on
import { defineConfig } from "vitest/config";

export default defineConfig({
  test: {
    globals: true, // describe, test, expect, vi, beforeEach become ambient
  },
});

The flag does two things and only one of them is obvious. At runtime it injects the identifiers into the global scope of each test file. At build time it does nothing for TypeScript, so the editor will underline every describe unless the compiler learns about them.

// tsconfig.json — the types entry that pairs with globals: true
{
  "compilerOptions": {
    "types": ["vitest/globals"] // ambient declarations for describe/test/expect/vi
  }
}

The rename itself is one identifier wide. Jest’s jest object becomes Vitest’s vi, and the members line up one for one with two exceptions that will be covered in the next sections — requireActual is asynchronous and retryTimes is an option rather than a call.

import { vi, test, expect } from "vitest";

// the members that map directly
vi.fn();                  // jest.fn()
vi.spyOn(obj, "method");  // jest.spyOn(obj, "method")
vi.clearAllMocks();       // jest.clearAllMocks()
vi.mocked(fn);            // jest.mocked(fn)
vi.useFakeTimers();       // jest.useFakeTimers()
vi.advanceTimersByTime(5); // jest.advanceTimersByTime(5)
vi.setSystemTime(0);      // jest.setSystemTime(0)

The members that do not map directly are few, and each has a documented replacement.

import { vi, test } from "vitest";

// jest.requireActual(path) → vi.importActual(path), which returns a promise
const actual = await vi.importActual<typeof import("./api")>("./api");

// jest.requireMock(path) → vi.importMock(path), also a promise
const mocked = await vi.importMock("./api");

// jest.retryTimes(3) → the retry option on the test or in the config
test("flaky on purpose", { retry: 3 }, () => { /* ... */ });

The migration guide’s advice is to enable globals: true, run the suite, and then remove it. The reason is not purity: a file with explicit imports is a file where the test’s dependencies are visible at the top, where vi is a real import that maps to a real module rather than an injected global, and where a stray identifier that should have been a local is a compile error instead of a silent reference to a runner global. Files that never remove the flag still work; they simply carry Jest’s implicit-dependency style into a runner that does not need it.

The vi object is importable whether or not the global is enabled, and importing it in one file while relying on the global in another is legal. That makes the migration incremental: turn the flag on for the suite, convert file by file to explicit imports, and delete the flag when the last file has been converted.


b. mockClear, mockReset, and mockRestore

Every mock carries three reset operations, and they sit in a strict hierarchy. mockClear removes the recorded calls. mockReset does what mockClear does and also resets the implementation. mockRestore does what mockReset does and additionally restores the original property descriptor, which only matters for a spy.

import { vi, test, expect } from "vitest";

test("mockClear keeps the implementation", () => {
  const mock = vi.fn(() => 42);   // an implementation is provided

  mock();                          // recorded; returns 42
  mock.mockClear();                // calls array emptied, implementation intact
  expect(mock()).toBe(42);         // still 42
});

mockClear is the safe one. It is what beforeEach(() => vi.clearAllMocks()) uses, and it is what a test wants in the overwhelmingly common case where the mock’s behaviour is fixed and only its call history needs to be reset between tests.

test("mockReset and mockRestore", () => {
  const obj = { greet: () => "real" };
  const spy = vi.spyOn(obj, "greet").mockReturnValue("mocked");

  expect(obj.greet()).toBe("mocked"); // the spy intercepts
  spy.mockReset();                     // implementation reset to the original
  expect(obj.greet()).toBe("real");    // calls through to the real function

  spy.mockRestore();                   // the descriptor is restored; spy detached
  expect(obj.greet()).toBe("real");
});

The divergence is in mockReset on a vi.fn(impl). Vitest restores impl; Jest removes the implementation and leaves the mock returning undefined.

// Vitest
const mock = vi.fn((n: number) => n * 2); // an implementation is provided
mock.mockReturnValue(10);                  // overridden
mock(1);                                   // 10
mock.mockReset();                          // back to the ORIGINAL implementation
mock(1);                                   // 2 — not undefined
// Jest — the same code, different outcome
const mock = jest.fn((n) => n * 2);
mock.mockReturnValue(10);
mock.mockReset();   // the implementation is REMOVED
mock(1);            // undefined

That difference has a concrete consequence for a factory that wraps the real function. The pattern vi.mock("./api", () => ({ getUser: vi.fn(realGetUser) })) produces a mock that, after a resetMocks in the config, calls realGetUser again — a live call inside a test that believed it had stubbed the module. Jest would have returned undefined, which fails loudly at the assertion. Vitest makes a real request, which fails quietly, or worse, succeeds and hides the problem.

// the shape that makes mockReset a real call
vi.mock("./api", async (importOriginal) => {
  const actual = await importOriginal<typeof import("./api")>();
  // the spy wraps the real function: mockReset restores this wrapper
  return { ...actual, getUser: vi.fn(actual.getUser) };
});

The fix for a test that genuinely wants an empty mock is to reset and then re-implement, which is explicit and works identically in both runners.

beforeEach(() => {
  mock.mockReset();                       // restore to the original state
  mock.mockReturnValue({ id: 1 });        // then set the value the test expects
});

The config flags are the same three names in both runners and default to false in both. Vitest adds two flags Jest has no equivalent for, because Vitest has vi.stubGlobal and vi.stubEnv, which Jest does not.

// vitest.config.ts — the lifecycle flags on the config
export default defineConfig({
  test: {
    clearMocks: true,    // vi.clearAllMocks() before every test
    resetMocks: true,    // vi.resetAllMocks() before every test
    restoreMocks: true,  // vi.restoreAllMocks() before every test
    unstubGlobals: true, // restore vi.stubGlobal values after every test
    unstubEnvs: true,    // restore vi.stubEnv values after every test
  },
});

The safe default for a migrated suite is clearMocks: true and unstubGlobals: true — clear the history, restore the globals, leave the implementations alone. resetMocks: true is the flag that collides with the divergence, and it should be turned on only after every vi.fn(impl) in the suite has been reviewed.


c. Module factories and hoisting

vi.mock takes a path and, optionally, a factory. The factory returns the module’s namespace: an object whose keys are the module’s exports. Everything the consuming code imports must be present, because a missing key is undefined at the import site rather than an error at the mock site.

import { vi, test, expect } from "vitest";
import { getUser } from "./api"; // the consumer imports a named export

vi.mock("./api", () => ({
  getUser: vi.fn().mockResolvedValue({ id: 1, name: "Alice" }),
}));

test("the named export is replaced", async () => {
  await expect(getUser()).resolves.toEqual({ id: 1, name: "Alice" });
});

A module with a default export needs a default key in the factory, and a module with both needs both. Returning only the named exports leaves the default import undefined, and the failure surfaces as x is not a function at the first call rather than as a mock error.

vi.mock("./api", () => ({
  default: { getUser: vi.fn() }, // for `import api from "./api"`
  getUser: vi.fn(),              // for `import { getUser } from "./api"`
}));

The hoisting is where the migration breaks. vi.mock is lifted above every import in the file by Vite’s transform, which means the factory body executes before any top-level const has been initialised. A factory that closes over a variable declared below it throws a reference error at the moment the mock runs, and the message names the identifier rather than the hoisting.

// FAILS: the factory runs before `fakeUser` is initialised
const fakeUser = { id: 1, name: "Alice" };
vi.mock("./api", () => ({ getUser: () => fakeUser })); // ReferenceError: Cannot access 'fakeUser' before initialization

vi.hoisted is the escape hatch. It lifts a value into the same pre-import position the factory occupies, so the two are adjacent in execution order rather than separated by the import block.

// WORKS: vi.hoisted moves the value up alongside the factory
const { fakeUser } = vi.hoisted(() => ({ fakeUser: { id: 1, name: "Alice" } }));
vi.mock("./api", () => ({ getUser: () => fakeUser })); // no temporal dead zone

This is the point where Jest’s mock-prefix convention has no replacement. Jest’s Babel plugin whitelists identifiers whose names begin with mock, so const mockUser = ... works in a factory without any explicit hoisting. Vitest does not parse identifiers and does not implement the convention, so the same code migrates into a ReferenceError. The renaming habit — mockUser, mockResponse — can stay, but the vi.hoisted call has to be added around the declaration.

// the migrated form of the Jest convention
const { mockUser } = vi.hoisted(() => ({ mockUser: { id: 1 } }));
vi.mock("./api", () => ({ getUser: () => mockUser }));

A partial mock keeps the real module and replaces one export. Vitest passes the original import function as the factory’s first argument, and the factory spreads the real namespace before overriding.

vi.mock("./api", async (importOriginal) => {
  const actual = await importOriginal<typeof import("./api")>(); // the real module
  return {
    ...actual,                          // every real export stays
    getUser: vi.fn().mockResolvedValue({ id: 1 }), // one export is replaced
  };
});

vi.importActual is the same thing reached directly rather than through the argument. It returns a promise, which is the async gap described earlier: Jest’s requireActual was synchronous, so a factory that used it needs an async keyword and an await in addition to the identifier change.

vi.mock("./api", async () => {
  const actual = await vi.importActual<typeof import("./api")>("./api"); // async
  return { ...actual, getUser: vi.fn() };
});

The newer shorthand is { spy: true }. Instead of writing a factory that wraps every export, the option automocks the module and wraps each function in a spy that calls through by default, so a test can override one function while the rest behave normally.

vi.mock("./api", { spy: true }); // every export is a spy that calls through

test("one function is overridden, the rest still run", async () => {
  const { getUser } = await import("./api"); // dynamic import after the mock
  vi.mocked(getUser).mockResolvedValue({ id: 1 }); // override this one
});

Two more forms round out the set. vi.mock(path) without a factory looks for a __mocks__ folder adjacent to the module — and for a package name, a __mocks__ folder at the project root — and automocks every export when no such folder exists. vi.doMock is the same registration but not hoisted, so it applies to dynamic imports that happen after the call; the matching vi.unmock, vi.doUnmock, and vi.resetModules complete the pair.

vi.mock("./api");              // __mocks__/api.ts, or an automock of every export
vi.doMock("./api", factory);   // not hoisted; affects later dynamic imports
vi.unmock("./api");            // remove a hoisted mock
vi.doUnmock("./api");          // remove a non-hoisted mock
vi.resetModules();             // clear the module registry between cases

A newer path form passes a dynamic import instead of a string, which lets the editor resolve the path and the factory’s return type be checked against the real module.

vi.mock(import("./api"), () => ({
  getUser: vi.fn(), // type-checked against ./api's exports
}));

d. The config file and the setup file

The config moves wholesale. A jest.config.js exports a flat object; a vitest.config.ts exports a Vite config with a test key, so the same file also holds the plugins, the aliases, and the build settings.

// vitest.config.ts — the shape of the file
import { defineConfig } from "vitest/config";
import tsconfigPaths from "vite-tsconfig-paths";

export default defineConfig({
  plugins: [tsconfigPaths()], // replaces jest's moduleNameMapper for tsconfig paths
  test: {
    environment: "jsdom",     // "node" | "jsdom" | "happy-dom" | "edge-runtime"
    setupFiles: ["./test/setup.ts"], // replaces setupFilesAfterEnv
    globals: true,            // the migration aid from section a
  },
  resolve: {
    alias: { "@": "/src" },   // replaces moduleNameMapper
  },
});

The setup file is one file instead of two. Jest splits setupFiles (before the framework is installed) from setupFilesAfterEnv (after), because the two run at different points relative to expect being extended. Vitest has a single setupFiles array and runs each entry once per test file, with the full vitest API available, so the distinction disappears.

// test/setup.ts — Jest's setupFilesAfterEnv content, unchanged in function
import { expect, afterEach } from "vitest";
import { cleanup } from "@testing-library/react";

afterEach(() => {
  cleanup(); // unmount anything a test rendered
});

expect.extend({
  // custom matchers registered here work in every test file
});

The environment options are a superset. Jest offers node and jsdom; Vitest offers those plus happy-dom, which is a lighter DOM implementation, and edge-runtime, which is the Cloudflare Workers runtime — neither has a Jest equivalent.

test: {
  environment: "happy-dom", // lighter than jsdom, faster to boot per file
}

The transform is gone rather than ported. Jest needs babel-jest or ts-jest configured to read TypeScript, and transformIgnorePatterns to opt packages out of being transpiled. Vitest reads TypeScript directly through esbuild and only transforms what it must, so the transform block has no counterpart and transformIgnorePatterns becomes server.deps.inline for the rare package that needs its dependency source processed.

test: {
  server: {
    deps: {
      inline: ["some-esm-only-package"], // the transformIgnorePatterns equivalent
    },
  },
}

Timeouts default to 5000 ms in both runners, which means a suite with jest.setTimeout(30000) at the top of a file needs that value moved. Vitest takes it as a config value or as the third argument to test.

test("a slow one", async () => { /* ... */ }, 30_000); // per-test, in ms
// or globally: test: { testTimeout: 30_000 }

Complete Example Session

// ============================================
// PART 1: THE CONFIG
// ============================================
// vitest.config.ts
import { defineConfig } from "vitest/config";

export default defineConfig({
  test: {
    globals: true,        // the migration aid; remove after converting imports
    environment: "jsdom", // replaces jest's testEnvironment
    clearMocks: true,     // history only; implementations are left alone
    unstubGlobals: true,  // no Jest equivalent; restores vi.stubGlobal
  },
});

// ============================================
// PART 2: THE GLOBAL FORM
// ============================================
// tsconfig needs "types": ["vitest/globals"] for this to compile
describe("migrated as-is", () => {
  it("uses ambient globals", () => {
    expect(1 + 1).toBe(2); // no import; the identifiers are injected
  });
});

// ============================================
// PART 3: THE IMPORT FORM
// ============================================
import { describe, it, expect, vi } from "vitest";

describe("explicit imports", () => {
  it("names its dependencies", () => {
    const fn = vi.fn(() => 42); // vi is imported, not injected
    expect(fn()).toBe(42);
  });
});

// ============================================
// PART 4: THE LIFECYCLE LADDER
// ============================================
test("clear, reset, restore", () => {
  const obj = { greet: () => "real" };
  const spy = vi.spyOn(obj, "greet").mockReturnValue("mocked");

  spy.mockClear();   // call history cleared, still returns "mocked"
  expect(obj.greet()).toBe("mocked");

  spy.mockRestore(); // descriptor restored, the spy is detached
  expect(obj.greet()).toBe("real");
});

// ============================================
// PART 5: THE ORIGINAL-IMPLEMENTATION TRAP
// ============================================
test("mockReset restores the original implementation", () => {
  const mock = vi.fn((n: number) => n * 2); // an implementation is supplied
  mock.mockReturnValue(10);                  // overridden for this test
  expect(mock(1)).toBe(10);                  // the override wins

  mock.mockReset();                          // Vitest: back to n * 2
  expect(mock(1)).toBe(2);                   // Jest would return undefined here

  mock.mockReset().mockReturnValue(10);      // the portable pattern: reset, then set
  expect(mock(1)).toBe(10);
});

// ============================================
// PART 6: THE MODULE FACTORY
// ============================================
import { getUser } from "./api";

vi.mock("./api", () => ({
  getUser: vi.fn().mockResolvedValue({ id: 1, name: "Alice" }), // every export present
}));

test("the factory replaces the module", async () => {
  await expect(getUser()).resolves.toEqual({ id: 1, name: "Alice" });
});

// ============================================
// PART 7: THE HOISTED VARIABLE
// ============================================
const { fakeUser } = vi.hoisted(() => ({
  fakeUser: { id: 2, name: "Bob" }, // moved above the imports by vi.hoisted
}));

vi.mock("./api", () => ({
  getUser: vi.fn().mockResolvedValue(fakeUser), // safe: fakeUser is initialised
}));

test("the hoisted value reaches the factory", async () => {
  await expect(getUser()).resolves.toEqual({ id: 2, name: "Bob" });
});

// ============================================
// PART 8: THE PARTIAL MOCK
// ============================================
vi.mock("./api", async (importOriginal) => {
  const actual = await importOriginal<typeof import("./api")>(); // the real namespace
  return {
    ...actual,                                      // every export kept real
    getUser: vi.fn().mockResolvedValue({ id: 3 }),  // one export replaced
  };
});

// ============================================
// PART 9: THE SPY SHORTHAND
// ============================================
vi.mock("./api", { spy: true }); // every export becomes a spy that calls through

test("override one function through the spy", async () => {
  const api = await import("./api");       // dynamic import after the mock
  vi.mocked(api.getUser).mockResolvedValue({ id: 4 }); // this call is replaced
});

// ============================================
// PART 10: THE CONFIG FLAGS
// ============================================
// vitest.config.ts — the three lifecycle flags plus the two stub flags
export default defineConfig({
  test: {
    clearMocks: true,    // vi.clearAllMocks() before every test
    resetMocks: false,   // leave off until every vi.fn(impl) is reviewed
    restoreMocks: true,  // vi.restoreAllMocks() before every test
    unstubGlobals: true, // restore vi.stubGlobal after every test
    unstubEnvs: true,    // restore vi.stubEnv after every test
  },
});

The ten parts covered the config, the ambient-global form, the explicit-import form, the three-function lifecycle, the mockReset divergence with the portable pattern, a plain module factory, a vi.hoisted variable, a partial mock through importOriginal, the { spy: true } shorthand, and the five config flags that decide which lifecycle runs between tests.


Quick Reference

The Global Rename

JestVitestNote
jest.fn()vi.fn()same
jest.spyOn()vi.spyOn()same
jest.mock()vi.mock()same name, different hoisting
jest.requireActual()vi.importActual()returns a promise
jest.mocked()vi.mocked()same
jest.retryTimes(n){ retry: n }an option, not a call
jest globalvi exportambient only with globals: true

The Mock Lifecycle

CallCalls clearedImplementationDescriptor
mockClear()yesuntoucheduntouched
mockReset()yesrestored to impluntouched
mockRestore()yesrestored to implrestored

The Factory Forms

FormBehaviour
vi.mock(p, factory)hoisted; factory returns the namespace
vi.mock(p)uses __mocks__, else automocks
vi.mock(p, { spy: true })automocks, wraps each export in a call-through spy
vi.doMock(p, factory)not hoisted; later dynamic imports only
vi.unmock(p) / vi.doUnmock(p)removes the registration
vi.hoisted(fn)lifts a value above the imports
importOriginalthe real namespace, inside an async factory

The Config Mapping

JestVitest
testEnvironmentenvironment (adds happy-dom, edge-runtime)
setupFilesAfterEnvsetupFiles
moduleNameMapperresolve.alias
transform / ts-jestnone needed; esbuild is built in
transformIgnorePatternsserver.deps.inline
testMatch / testRegexinclude
jest.setTimeout(n)testTimeout or the third argument

Best Practices

✅ Do This:

// Enable globals for the migration, then remove them file by file
test: { globals: true }                                     // ✅

// Add the ambient types when globals are on
"types": ["vitest/globals"]                                 // ✅

// Hoist any value a factory closes over
const { user } = vi.hoisted(() => ({ user: { id: 1 } }));   // ✅

// Reset and re-implement, which works in both runners
mock.mockReset().mockReturnValue(42);                       // ✅

// Return every export from the factory, default included
vi.mock("./api", () => ({ default: {...}, getUser: vi.fn() })); // ✅

// Await the original in a partial mock
const actual = await importOriginal<typeof import("./api")>(); // ✅

// Prefer the spy shorthand over a hand-written wrapper factory
vi.mock("./api", { spy: true });                            // ✅

❌ Don’t Do This:

// Close over a top-level const from a factory
const user = { id: 1 };
vi.mock("./api", () => ({ getUser: () => user }));          // ❌ ReferenceError

// Rely on Jest's mock-prefix hoisting convention
const mockUser = { id: 1 };
vi.mock("./api", () => ({ getUser: () => mockUser }));      // ❌ still a TDZ error

// Assume mockReset empties the implementation
vi.fn(realFn).mockReset(); // now calls realFn                     // ❌

// Keep moduleNameMapper in a test block
test: { moduleNameMapper: { "@": "/src" } }                 // ❌ silently ignored

// Call requireActual synchronously
vi.mock("./api", () => vi.importActual("./api"));           // ❌ returns a promise

// Turn on resetMocks before reviewing vi.fn(impl) calls
test: { resetMocks: true }                                  // ❌ real calls reappear

Common Pitfalls

PitfallWhy It HappensFix
Cannot access 'x' before initializationthe factory closes over a top-level constwrap the declaration in vi.hoisted
x is not a function on a default importthe factory omitted the default keyreturn { default, ...named }
A test reaches the network after migrationmockReset restored the real implementationmockReset() then re-implement
describe is not defined in the editorglobals: true without the ambient typesadd vitest/globals to types
Path alias is unresolved at runtimemoduleNameMapper left in a test blockmove it to resolve.alias
The setup file never runssetupFilesAfterEnv usedrename to setupFiles
A factory returns a promise as the modulevi.importActual not awaitedmake the factory async
Mocks leak between test filesa global was never stubbed backunstubGlobals: true

Real-World Examples

1. Enable the migration flag

test: { globals: true }

2. Pair it with the ambient types

{ "compilerOptions": { "types": ["vitest/globals"] } }

3. Hoist a fixture

const { user } = vi.hoisted(() => ({ user: { id: 1, name: "Alice" } }));

4. Factory with a default export

vi.mock("./client", () => ({ default: vi.fn(), get: vi.fn() }));

5. Partial mock

vi.mock("./api", async (importOriginal) => ({
  ...(await importOriginal<typeof import("./api")>()),
  getUser: vi.fn(),
}));

6. Spy shorthand

vi.mock("./api", { spy: true });

7. The portable reset

mock.mockReset().mockResolvedValue({ id: 1 });

8. Config flags

test: { clearMocks: true, restoreMocks: true, unstubGlobals: true }

9. Alias

resolve: { alias: { "@": "/src" } }

10. Per-test timeout

test("slow", async () => { /* ... */ }, 30_000);

Visual

The Hoisting Order

┌────────────────────────────────────────────────────────────┐
│  SOURCE FILE                   AFTER THE TRANSFORM         │
│                                                            │
│  import { getUser }            vi.mock("./api", factory)   │
│    from "./api"                import { getUser }          │
│  vi.mock("./api", factory)       from "./api"              │
│                                                            │
│  The mock call is lifted above the import. The factory     │
│  body therefore runs before any top-level const exists,    │
│  which is why a closure over one throws a TDZ error.       │
└────────────────────────────────────────────────────────────┘

The Mock Lifecycle

┌────────────────────────────────────────────────────────────┐
│  LADDER                                                    │
│                                                            │
│  mockClear     calls emptied                               │
│      │         implementation untouched                    │
│      ▼                                                     │
│  mockReset     calls emptied                               │
│      │         implementation restored to impl             │
│      │         (Jest: implementation removed)              │
│      ▼                                                     │
│  mockRestore   calls emptied                               │
│                implementation restored to impl             │
│                descriptor restored, spy detached           │
│                                                            │
│  Each level does everything the level above does.          │
└────────────────────────────────────────────────────────────┘

Globals Versus Imports

┌────────────────────────────────────────────────────────────┐
│  globals: false                globals: true               │
│                                                            │
│  import { vi, test,            vi.mock("./api")            │
│    expect } from "vitest"      test("x", () => {           │
│                                 expect(1).toBe(1)          │
│  vi.mock("./api")            })                            │
│  test("x", () => {                                         │
│    expect(1).toBe(1)          each identifier comes from   │
│  })                           the injected global scope    │
│                                                            │
│  Explicit: the dependency list is visible at the top.      │
│  Ambient: no imports, and no compile error for a typo.     │
└────────────────────────────────────────────────────────────┘

The Config File

┌────────────────────────────────────────────────────────────┐
│  jest.config.js              vitest.config.ts              │
│  ───────────────             ────────────────              │
│  testEnvironment   ───────►  test.environment              │
│  setupFilesAfterEnv ──────►  test.setupFiles               │
│  moduleNameMapper  ───────►  resolve.alias                 │
│  transform         ───────►  (Vite handles it)             │
│  transformIgnorePatterns ─►  test.server.deps.inline       │
│  jest.setTimeout   ───────►  test.testTimeout              │
│                                                            │
│  The file is a Vite config with a test key, so a key       │
│  that is not in test is a Vite key, not a Jest key.        │
└────────────────────────────────────────────────────────────┘

Summary

ItemValue
Globalstest.globals: true, plus vitest/globals in types
Global objectvi, replacing jest
mockClearcalls only
mockResetcalls plus implementation restored to impl
mockRestoreplus the original descriptor, spies detached
vi.mockhoisted above the imports
vi.hoistedlifts a value into the hoisted position
Partial mockimportOriginal, awaited inside an async factory
Spy shorthandvi.mock(path, { spy: true })
requireActualvi.importActual, which returns a promise
Setup filesetupFiles, replacing setupFilesAfterEnv
Aliasresolve.alias, replacing moduleNameMapper

Key takeaways:

  • globals: true is a bridge, not a destination. It injects describe, test, expect, and vi into each file and needs vitest/globals in the TypeScript types array to compile. The migration guide’s advice is to enable it, run the suite, and then convert file by file until it can be removed — a file with explicit imports names its dependencies at the top and turns a typo into a compile error.
  • The rename is one identifier wide. jest becomes vi and the members line up, with two documented exceptions: jest.requireActual and jest.requireMock become vi.importActual and vi.importMock and return promises, and jest.retryTimes(n) becomes the { retry: n } test option.
  • mockReset restores the original implementation. On a vi.fn(impl) the mock returns impl again after a reset, where Jest removed the implementation and returned undefined. The consequence is a real code path where a test expected a stub, so the portable pattern is mock.mockReset().mockReturnValue(value) and the config flag resetMocks is turned on only after every vi.fn(impl) has been reviewed.
  • vi.mock is hoisted; vi.hoisted is how a factory reaches a value. The factory body runs before any top-level const is initialised, and Vitest does not implement Jest’s mock-prefix convention, so the declaration itself has to move into a vi.hoisted call. The error without it is a temporal-dead-zone ReferenceError naming the identifier rather than the hoisting.
  • The factory must return the whole namespace. A missing default key leaves a default import undefined and the failure surfaces as x is not a function at the first call. The partial form spreads await importOriginal<typeof import(...)>() before overriding, and { spy: true } covers the case where the wrapper would have been mechanical.
  • The config file is a Vite config with a test key. environment, setupFiles, resolve.alias, and server.deps.inline replace testEnvironment, setupFilesAfterEnv, moduleNameMapper, and transformIgnorePatterns; a Jest key written inside the test block is silently ignored rather than rejected, which is the failure mode worth watching for.

Remember: The migration is a find-and-replace for ninety percent of the suite and a careful read of three mechanisms for the rest. Turn on the globals, rename jest to vi, and then stop replacing and start reading: hoist every value a factory closes over, reset and re-implement every mock rather than trusting mockReset to empty it, and move the config keys to the names Vite actually uses. The three differences are deliberate, documented, and each has a one-line fix — which makes them cheap to apply during migration and expensive to discover three weeks later.

Was this helpful?


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!