What is an Nx Jest to Vitest migration, and who should do one?

The syntax is the easy part. Most describe, it and expect calls carry over unchanged. The real work in an Nx Jest to Vitest migration is module mocking, decorator metadata and module format. That is why the change should go one library at a time, with each step easy to undo, rather than as a single workspace-wide rewrite.

In concrete terms, the migration changes the test target of each Nx project. It moves from the Jest executor in @nx/jest to the Vitest executor in @nx/vite. The code under test stays the same. You replace the runner, its config file and the test-setup glue, and you leave service logic alone. If a production file has to change to make a test pass, treat that as a signal to investigate, not as a normal part of the work.

Teams usually switch for three reasons:

  • One toolchain. If your frontend apps already build with Vite, moving backend libraries onto Vitest lets them share one transform pipeline, one resolver config and one set of plugins. Jest needs its own separate setup.
  • ESM-native execution. Vitest runs ES modules directly. Jest usually needs a transpile step and extra configuration before it handles ESM-only dependencies cleanly.
  • Watch-mode ergonomics. Vitest reruns only the tests affected by a changed file, which shortens the edit-test loop on large libraries.

This guide is for backend and platform engineers who own Nx workspaces containing Node services and shared libraries, especially code that relies on dependency injection, decorators or heavy module mocking.

How does the migration work?

Three layers are involved, and the migration changes only the bottom one.

  1. The Nx target. Every project exposes a test target, either declared in project.json or inferred by a plugin. Nx decides whether to run it, using the project graph for nx affected and the computed hash of the target's inputs to look up a cached result. Nx does not care which runner sits behind the target, as long as the inputs and outputs are declared correctly.
  2. The executor. The target's executor (or inferred command) starts the runner. With @nx/jest, that is Jest reading jest.config.ts. With @nx/vite, that is Vitest reading vite.config.ts or vitest.config.ts. Swapping the executor is what "migrating a library" means at the Nx level.
  3. The runner. This is where behaviour actually differs:
    • Jest loads each test file through its own module registry, applying a configured transform (ts-jest, babel-jest or an SWC transform) to every file it requires. Its module system is CommonJS-first, which is why ESM-only packages often need transformIgnorePatterns changes or the experimental ESM mode.
    • Vitest uses Vite's module pipeline. Files are transformed on demand, TypeScript by esbuild unless a plugin replaces it, and executed as ES modules. Vite plugins and resolver settings apply to tests the same way they apply to builds. Before execution, Vitest rewrites each test file so that vi.mock calls are hoisted above the imports, which is why mock factories cannot read ordinary top-level variables.
    • Both runners distribute test files across workers. Vitest offers a threads pool (worker threads in one process) and a forks pool (child processes), and isolates each test file's module state by default.

Because Nx sees only "a test target with inputs and outputs", Jest and Vitest projects can coexist in one workspace. nx affected -t test runs both kinds, and caching works the same way for each, provided the new config files are declared as inputs.

When should you migrate, and when should you stay on Jest?

Migrate when the change removes friction you already have. Three signals are worth acting on:

  • The workspace already uses Vite. Frontend projects running on Vite share the plugin model and config style, so backend libraries stop being the exception.
  • ESM-first dependencies fight your Jest transforms. Long transformIgnorePatterns lists and experimental ESM flags are a maintenance cost. Vitest treats ESM as the default.
  • You want one config style. A single vite.config.ts shape across projects is easier to review than a mix of Jest presets.

When should you avoid the migration?

Avoid or postpone the migration when the runner is not your problem:

  • Infrastructure dominates the suite. If most wall-clock time goes to database, network or container setup, a faster runner saves little.
  • You rely on Jest's implicit mocking. Jest automocking and root-level __mocks__ for node_modules apply without a call in the test. Vitest requires an explicit vi.mock for each module, so every affected test has to change.
  • NestJS or TypeORM needs decorator metadata. esbuild does not emit emitDecoratorMetadata output. The usual fix is an SWC plugin, and adding it gives back much of the simplicity you were migrating for.
  • Nobody can own the dual-runner period. If the team cannot commit to finishing the migration, a half-migrated workspace with two runners, two config styles and two mocking APIs is worse than staying on Jest.

There are two alternatives. You can stay on Jest and switch its transform to SWC, which often removes the type-checking cost of ts-jest. For small libraries with few mocks, Node's built-in test runner avoids a runner dependency entirely.

Do not assume any option is faster. Time your own suite, both cold and with the Nx cache, before you migrate and after.

Jest (+ SWC transform) Vitest Node built-in runner
Transform ts-jest or SWC esbuild through Vite None built in; run compiled output or a loader
ESM support Experimental flag, transform workarounds Default Native
Mocking model Automock, implicit __mocks__ Explicit vi.mock, Jest-like API mock API, limited module mocking
Decorator metadata Supported via ts-jest or SWC Requires SWC plugin Depends on your build step
Migration cost Low (config only) Moderate (mocks, globals) High (assertions and mocks rewritten)

How do you choose a migration order using the Nx project graph?

Migrate from the bottom of the dependency graph upward. Run nx graph and find the leaf libraries, the ones nothing else in the workspace imports from. These usually include utilities, DTO packages and small domain modules. Converting them first means a broken mock or a missing decorator transform affects only that project's suite. No other project's tests can fail because of it.

Wave 3 (apps):        api-gateway       billing-worker
                          |    \           /     |
Wave 2 (shared):      data-access    auth-core   |
                          |    \        /        |
Wave 1 (leaves):      date-utils   config-schema   money

Keep the target name test on every project and change only the runner underneath it. nx affected -t test and your CI pipeline then work the same way whether a given project runs Jest or Vitest. Nobody needs to remember which command applies to which library.

The dual-runner period has real costs:

  • Jest and Vitest dependencies are both installed.
  • Contributors maintain two config styles, jest.config.ts and vite.config.ts.
  • New contributors copy whichever test file they open first. That spreads jest.fn() into libraries that have already moved to vi.fn().

Set an explicit end date for the migration. Track the remaining Jest projects in one visible place, such as a checklist in the repository or a lint rule that flags Jest imports in migrated projects.

This ordering keeps each step small. One library's change is reviewable in minutes, and Nx caches the results of projects you didn't touch. Reverting a project is a single project.json change that points the target back at Jest.

#!/usr/bin/env bash
set -euo pipefail

npx nx graph --file=graph.json

echo "Wave 1 candidates (no workspace dependencies):"
jq -r '.graph as $g
  | $g.nodes | to_entries[]
  | select(.value.type == "lib")
  | .key as $p
  | select([$g.dependencies[$p][]? | .target | select(startswith("npm:") | not)] | length == 0)
  | "  " + $p' graph.json

echo "Projects still on Jest:"
remaining=0
for p in $(npx nx show projects --with-target test); do
  runner=$(npx nx show project "$p" --json \
    | jq -r '.targets.test | (.executor // "") + " " + (.options.command // "")')
  if grep -qi jest <<<"$runner"; then
    echo "  $p"
    remaining=$((remaining + 1))
  fi
done
echo "Remaining Jest projects: $remaining"

npx nx affected -t test

A script that exports the Nx project graph to find libraries with no workspace dependencies, lists which projects' test targets still run Jest, and then runs nx affected -t test across both runners.

How do you add Vitest to one backend library with @nx/vite?

Start by running nx list @nx/vite. It prints the generators the installed plugin actually ships, so you use the real configuration generator name and not one copied from an older blog post. Run that generator against a single project, then read its output before committing. Depending on your Nx version, it may write a vite.config.ts or a vitest.config.ts, add a test target to project.json or rely on inferred targets, and edit tsconfig files. Check every change.

The accompanying config example annotates these backend choices:

  • environment: 'node'. Backend code has no use for jsdom. Setting it explicitly means a future default change can't silently pull in a browser environment.
  • Globals. globals: true keeps the diff small because existing describe/it/expect calls work unchanged. It also requires vitest/globals in the spec tsconfig's types, and leftover @types/jest will conflict with those declarations. Explicit imports from vitest add noise to every file, but they make each test's dependencies clear and remove the type collision.
  • Setup files. Move Jest's setupFiles and setupFilesAfterEnv entries into Vitest's single setupFiles array, in the same order. Vitest runs them before each test file, after the framework is available.
  • Module resolution. If your workspace maps imports through paths in tsconfig.base.json, add the Nx tsconfig-paths Vite plugin that @nx/vite provides. If it uses TypeScript project references with packages linked through the package manager's workspaces, leave that plugin out and let normal package resolution work.

The import errors tell you which setup you have. A "failed to resolve import" for @org/foo in an alias workspace means the paths plugin is missing. In a project-references workspace, the same error usually means the library's package.json doesn't declare the dependency or its exports don't point at a resolvable entry.

// libs/orders-api/vitest.config.ts
// Review against what your Nx version's generator wrote; option names here are stable Vitest/Vite ones.
import { defineConfig } from 'vitest/config';
// Only for workspaces that resolve @org/* through `paths` in tsconfig.base.json.
// Remove this import and the plugin below if you use TS project references
// with packages linked through package manager workspaces.
import { nxViteTsPaths } from '@nx/vite/plugins/nx-tsconfig-paths.plugin';

export default defineConfig({
  root: __dirname,
  cacheDir: '../../node_modules/.vite/libs/orders-api',
  plugins: [nxViteTsPaths()],
  test: {
    name: 'orders-api',
    // Backend code: pin Node explicitly so no browser environment (jsdom) is ever pulled in.
    environment: 'node',
    // true = existing describe/it/expect calls work without imports (smaller diff).
    // Requires "types": ["vitest/globals"] in tsconfig.spec.json and removing @types/jest.
    // Set to false and import { describe, it, expect, vi } from 'vitest' for explicit deps.
    globals: true,
    include: ['src/**/*.{test,spec}.ts'],
    // Jest setupFiles + setupFilesAfterEnv merged here, original order preserved.
    // These run before each test file, with the Vitest API already available.
    setupFiles: ['./test/load-env.ts', './test/register-matchers.ts'],
    coverage: {
      provider: 'v8',
      reportsDirectory: '../../coverage/libs/orders-api',
    },
  },
});

An annotated vitest.config.ts for a single Node backend library that sets the node environment, chooses globals, merges the Jest setup files, and adds the Nx tsconfig-paths plugin for path-alias workspaces.

How does the Jest API map to Vitest, and where does mocking differ?

Most of the API translates by swapping the jest global for vi. The cost is in the few places where the semantics differ.

Jest Vitest Note
jest.fn() / jest.spyOn() vi.fn() / vi.spyOn() Same call shape
jest.useFakeTimers() vi.useFakeTimers() Check which timer APIs you fake
jest.mock(path, factory) vi.mock(path, factory) Hoisted; factory may be async
jest.requireActual(path) await vi.importActual(path) Returns a promise
done callback async test or returned promise Rewrite; don't wrap

vi.mock is hoisted above your imports. A factory that references a const declared in the test file reads it before it is initialised. Move shared mock objects into vi.hoisted(() => ({ ... })) so they are created early enough. The hoisted-mock example shows this rewrite.

For partial mocks, make the factory async, spread await vi.importActual(path), and override only the exports you need. The partial-mock example shows this pattern.

Automocking differs too. Jest picks up a root __mocks__ directory for packages in node_modules automatically. Vitest applies those mocks only when you call vi.mock for that module. A suite that relied on the implicit mock will either hit the real module or fail in ways unrelated to the code under test.

Under ESM, a factory must return default explicitly when the module has a default export. Named exports do not get this treatment.

Expect snapshot headers and error formatting to change. Regenerate snapshots in a separate commit from the runner swap so reviewers can see real behaviour changes instead of approving a wall of diff noise.

import { describe, it, expect, vi, beforeEach } from 'vitest';

// BEFORE (Jest): the `mock` prefix let the factory reference a top-level const.
// const mockSend = jest.fn();
// jest.mock('./mailer', () => ({ send: mockSend }));

// AFTER (Vitest): vi.mock is hoisted above this file's declarations, so create
// the shared mock inside vi.hoisted, which is hoisted along with it.
const { mockSend } = vi.hoisted(() => ({ mockSend: vi.fn() }));
vi.mock('./mailer', () => ({ send: mockSend }));

// BEFORE (Jest): synchronous partial mock.
// jest.mock('./config', () => ({
//   ...jest.requireActual('./config'),
//   getRegion: () => 'eu-west-1',
// }));

// AFTER (Vitest): the factory is async because importActual returns a promise.
// Keep the real exports and override only getRegion.
vi.mock('./config', async () => {
  const actual = await vi.importActual<typeof import('./config')>('./config');
  return { ...actual, getRegion: () => 'eu-west-1' };
});

import { notifyUser } from './notify';

describe('notifyUser', () => {
  beforeEach(() => {
    mockSend.mockReset();
  });

  it('sends through the mailer with the overridden region', async () => {
    mockSend.mockResolvedValue({ id: 'msg-123' });
    await notifyUser('user-42');
    expect(mockSend).toHaveBeenCalledWith(
      expect.objectContaining({ region: 'eu-west-1' }),
    );
  });
});

A Jest suite rewritten for Vitest: vi.hoisted creates the shared mock that the hoisted vi.mock factory uses, and an async factory spreads await vi.importActual to build a partial mock.

How do you fix decorator metadata, ESM and worker-pool problems in backend suites?

Vite transforms TypeScript with esbuild, and esbuild does not emit decorator metadata. NestJS and TypeORM resolve constructor dependencies from the design:paramtypes metadata that emitDecoratorMetadata produces. Without it, injection fails, often as undefined providers rather than a clear error. The fix is to swap in an SWC-based transform plugin in the library's Vitest config, with decorators and decoratorMetadata enabled in its options. The cost is another dev dependency and a second compiler configuration that must stay aligned with tsconfig.

Vitest runs tests as ES modules, which causes three common failures:

  • Missing __dirname and __filename. Derive them with fileURLToPath(new URL('.', import.meta.url)) from node:url.
  • require inside tests. Convert these calls to import. Where a synchronous load is genuinely needed, build a scoped require with createRequire(import.meta.url) from node:module.
  • CommonJS default exports. These can arrive wrapped, so mod.default may be the real export or may be undefined. Prefer named imports where the package provides them, and normalise with mod.default ?? mod at the boundary.

Pool choice matters more for backend code than for UI code. threads starts faster, but workers share one process, so native addons, process.env mutations and global singletons can interact. Setting pool: 'forks' gives each worker its own process, which is the safer default for database drivers and code that patches globals. The trade-off is slower startup.

Setting isolate: false speeds up suites but reuses module state across files. That can bring back the test-order dependencies the migration was meant to expose.

// libs/orders-api/vitest.config.ts
import { fileURLToPath } from 'node:url';
import { defineConfig } from 'vitest/config';
import swc from 'unplugin-swc';

// ESM has no __dirname, so derive this file's directory from import.meta.url
const libRoot = fileURLToPath(new URL('.', import.meta.url));

export default defineConfig({
  root: libRoot,
  plugins: [
    // Replace esbuild with SWC so design:paramtypes metadata is emitted
    // and NestJS/TypeORM constructor injection resolves real providers.
    // Keep these flags aligned with experimentalDecorators and
    // emitDecoratorMetadata in the library's tsconfig.
    swc.vite({
      module: { type: 'es6' },
      jsc: {
        parser: { syntax: 'typescript', decorators: true },
        transform: { legacyDecorator: true, decoratorMetadata: true },
      },
    }),
  ],
  test: {
    environment: 'node',
    include: ['src/**/*.spec.ts'],
    // One process per worker: native DB drivers, process.env changes and
    // patched globals cannot leak between test files. Startup is slower.
    pool: 'forks',
    // Default is true. Setting it to false reuses module state across files
    // and can reintroduce test-order dependencies.
    isolate: true,
  },
});

A per-library Vitest config that uses unplugin-swc to emit decorator metadata, derives the library directory with an ESM-safe fileURLToPath pattern, and runs tests in the forks pool with isolation left on.

How do you keep the Nx cache correct and verify parity before removing Jest?

Fixing isolation is only half the job. The other half is making sure Nx caches the new target correctly. A test target's cache hash comes from its declared inputs. If vitest.config.ts or a setup file such as src/test-setup.ts is missing from those inputs, editing it will not invalidate the cache, and Nx will replay a stale pass.

The fix has two parts:

  • Inputs: add the config and setup files explicitly. In project.json or targetDefaults, that looks like "inputs": ["default", "^production", "{projectRoot}/vitest.config.ts"].
  • Outputs: declare coverage as an output, for example "outputs": ["{workspaceRoot}/coverage/{projectRoot}"], so cache hits restore the reports.

If you rely on the @nx/vite inference plugin, check what it infers rather than assuming. These fragments are illustrative, so verify the exact syntax against your installed Nx version.

Removed Jest files cause the opposite problem. A leftover {workspaceRoot}/jest.preset.js entry in sharedGlobals or targetDefaults means every edit to a file nobody runs anymore busts the cache for every project. Remove those entries as part of each migration PR.

Parity checklist

  1. For each library, run both runners and compare test counts, skipped counts and coverage percentages. A drop in test count usually means a glob mismatch, not faster tests.
  2. Run both runners in CI for a fixed window, such as two weeks or a set number of merges. Decide the window in advance so the dual setup does not become permanent.
  3. After the last library migrates, delete the Jest configs, jest.preset.js and Jest-only dependencies such as ts-jest and @types/jest.

Cost

During the dual-runner window, CI time and maintenance both increase. Small per-library PRs keep the work reviewable, and reruns of unchanged libraries come from the cache, which limits the added CI cost.

How can the migration save engineering time?

The savings come from removing recurring work, not from a one-off speedup. Look for them in four places:

  • Less transform maintenance. ESM-only dependencies no longer need entries in transformIgnorePatterns or experimental Jest flags. Each dependency upgrade that used to break the Jest transform stops being a debugging session.
  • One config model. When frontend and backend projects share Vite's resolver and plugin setup, a path-alias or plugin change is made once instead of being mirrored in Jest's moduleNameMapper and transform config.
  • A shorter edit-test loop. Vitest's watch mode reruns tests affected by the changed file, so engineers wait less between an edit and a result on large libraries.
  • Fewer hidden mocks. Explicit vi.mock calls make a test's dependencies visible in the file. Debugging a failure that came from an implicit __mocks__ directory takes time that explicit mocks avoid.

To decide whether the migration pays off, estimate it with your own numbers. The following is an illustrative estimate using assumed inputs, not a measured result:

  • Assumed team size: 10 backend engineers.
  • Assumed watch-mode reruns per engineer per day: 40.
  • Assumed time saved per rerun after migration: 3 seconds.
  • Assumed time spent per month fixing Jest transform breakage after dependency upgrades: 4 hours.

Watch-mode savings: 10 × 40 × 3 s = 1,200 s, or 20 minutes of team time per working day. Over an assumed 20 working days, that is about 6.7 hours per month, plus the assumed 4 hours of transform maintenance removed, for roughly 10.7 hours per month. Set that against the one-off cost of migrating each library and the temporary dual-runner overhead described above.

If your measured per-rerun difference is near zero, or your suite time is dominated by database and container setup, the watch-mode term disappears and the case rests on maintenance savings alone. Measure before and after on your own workspace, cold and with the Nx cache, and use those figures instead of the assumed ones.

How OneEnv can help

Disclosure: OneEnv is the product behind this blog.

OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.

Applied to nx jest to vitest migration, this is where it helps:

Saves time

  • Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
  • One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
  • Changing a shared variable is one edit and one review instead of editing every service's .env by hand.

Saves cost

  • Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
  • Less duplicated configuration to maintain: one shared definition inherited by many services.
  • A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
  • OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.

These are qualitative benefits, not measured results — how much you save depends on how many services share the value.

Want to try it? Start at oneenv.io.