Where does test time actually go in an Nx workspace?

Total CI test time is the sum of several stages, and the test runner owns only some of them:

nx affected -t test
   │  project graph + git diff → affected projects      [Nx]
   ▼
cache check (local / remote)                           [Nx]
   ├── hit  → replay logs + outputs ──────────► done
   └── miss
        ▼
   runner process start + config load                  [runner] ◄─ swap changes
   TypeScript transform                                [runner] ◄─ swap changes
   module resolution / graph build                     [runner] ◄─ swap changes
   test isolation (workers, module registry reset)     [runner] ◄─ swap changes
   test bodies (DB fakes, I/O, your logic)             [your code]

Swapping Jest for Vitest affects only the four runner stages, and only for cache misses. Scheduling, graph computation and cache replay stay the same. Slow test bodies, such as real database setup or sleeps, stay slow.

Per-project overhead adds up because Nx runs each project as a separate task. Each task starts its own runner, loads its own config and warms its own transform. A workspace with many small backend libraries pays that fixed cost once per library, even when each library has only a few seconds of actual tests.

Illustrative estimate (assumed numbers, not a benchmark)

Runner-attributable time ≈ misses × (startup + transform + resolution + isolation)

Assume 30 affected projects, of which 24 are cache hits and 6 are misses, with 4 s of runner overhead per miss. That gives 6 × 4 = 24 s. Even if a new runner cut overhead in half, you would save 12 s.

If the same run had 30 misses, the overhead would be 30 × 4 = 120 s, and halving it would save 60 s. A high cache hit rate shrinks the share of CI time a runner swap can affect.

┌──────────────────────────────────────────────┐
│ nx affected -t test                    [Nx]  │
│ project graph + git diff → affected list     │
└──────────────────────┬───────────────────────┘
                       ▼
┌──────────────────────────────────────────────┐
│ cache check (local / remote)           [Nx]  │
└──────────┬───────────────────────┬───────────┘
       hit │                       │ miss
           ▼                       ▼
┌────────────────────┐  ┌───────────────────────────────────┐
│ replay logs and    │  │ one task per project (repeats N×) │
│ outputs → done     │  │ ┌───────────────────────────────┐ │
│ (runner not run)   │  │ │ process start + config load * │ │
└────────────────────┘  │ │ TypeScript transform        * │ │
                        │ │ module resolution / graph   * │ │
                        │ │ isolation (workers, reset)  * │ │
                        │ └───────────────────────────────┘ │
                        │ test bodies (DB fakes, I/O, logic)│
                        └───────────────────────────────────┘

 * = runner stage: changes when Jest is swapped for Vitest
 Hit path and Nx stages: unchanged by a runner swap
 Runner cost ≈ misses × (startup + transform + resolution + isolation)

An Nx test run goes through affected-project detection and a cache check, and the runner stages that a Jest-to-Vitest swap can change run only on cache misses, once per project task.

How do Jest and Vitest execute TypeScript backend tests?

Both runners spend most of their per-file overhead in two places: turning TypeScript into JavaScript, and building a fresh module graph for each test file. Their architectures differ mainly in how they handle those two steps.

Jest passes every imported file through a transformer. With ts-jest in its default mode, that step can include a type-check, so each worker does compiler work before any assertion runs. SWC-based transformers only strip types, which makes them much cheaper. Jest then loads modules through its own CommonJS-oriented registry and gives each test file a separate registry inside a worker process. That isolation prevents state leaking between files, but it also means shared imports such as an ORM client or a framework container get evaluated again in every file. Native ESM support in Jest still needs extra configuration.

Vitest transforms files through a Vite-based pipeline that uses esbuild. esbuild strips types and never type-checks. Vitest handles ESM natively and runs files in either a threads or a forks pool. Isolation is on by default, but you can turn it off when your tests do not depend on clean module state.

Aspect Jest Vitest
Transform ts-jest (may type-check) or SWC (strip only) esbuild via Vite (strip only)
Module system CommonJS-first; ESM needs extra setup Native ESM
Pools Worker processes threads or forks
Isolation default Per-file registry, always Per-file, configurable
Globals Injected by default Opt-in via config
Mocking API jest.fn, jest.mock vi.fn, vi.mock

The practical consequence is that a Jest setup using ts-jest with type-checking, compared against Vitest, is mostly a comparison of type-checking against no type-checking. Before you credit the speed difference to the runner, switch Jest to an SWC transformer and measure again.

How do you measure Jest vs Vitest speed fairly in Nx?

Run both runners against the same project, at the same commit, with Nx caching turned off. Otherwise a cache hit records near-zero time for whichever runner happened to go second. nx test orders-api --skip-nx-cache forces a real execution. Wrapping it in the shell's time builtin gives you wall time for that one target. Repeat each run several times and discard the first. The first run is a cold start: it pays for module resolution and the transform cache. Later runs are warm and reflect what a developer sees on the second save. Report both, because Vitest and Jest each keep their own on-disk transform caches, and those caches behave differently.

Record per-project runner wall time separately from total pipeline time, such as nx run-many -t test --skip-nx-cache or a full CI job. Pipeline time also includes install, task scheduling, and parallelism limits, which hide or inflate the runner difference. Use hardware close to your CI agents. A laptop with many fast cores flatters whichever runner parallelizes better.

Illustrative estimate. Assume 200 test projects, each saving 2.5 s of startup after migration, running 4 projects in parallel. A full uncached run saves about 500 s of compute, or roughly 125 s of wall time. Now take a typical PR: 15% of projects are affected (30), and 60% of those are restored from the remote cache. Only 12 projects actually execute, which saves about 30 s of compute and under 10 s of wall time. If affected scope is small and cache hit rates are high, most of the runner savings disappear from the pipeline total.

These inputs are assumptions. Your startup costs, project graph, and cache behavior will differ, so measure your own workspace rather than borrowing anyone's numbers.

#!/usr/bin/env bash
# Usage: ./time-tests.sh <project> <runs> <label>
# Run once on the Jest commit and once on the Vitest commit, same machine.
set -euo pipefail

PROJECT="${1:-orders-api}"
RUNS="${2:-6}"
LABEL="${3:-$(git rev-parse --short HEAD)}"   # e.g. jest or vitest
OUT=timings.csv

# 1) Per-project runner wall time. --skip-nx-cache forces real execution,
#    so an Nx cache hit can't record near-zero time for one runner.
for i in $(seq 1 "$RUNS"); do
  start=$(date +%s%N)                     # GNU date, nanoseconds
  npx nx test "$PROJECT" --skip-nx-cache > /dev/null 2>&1
  end=$(date +%s%N)
  ms=$(( (end - start) / 1000000 ))

  # Run 1 is cold (module resolution + runner transform cache).
  # Later runs are warm. Keep both, but report them separately.
  kind=warm; [ "$i" -eq 1 ] && kind=cold
  echo "$LABEL,$PROJECT,$i,$kind,$ms" >> "$OUT"
done

# 2) Pipeline time, recorded separately. Includes scheduling and the
#    parallelism limit, so it will not equal the sum of per-project times.
#    Match --parallel to what your CI agents actually use.
start=$(date +%s%N)
npx nx run-many -t test --skip-nx-cache --parallel=4 > /dev/null 2>&1
end=$(date +%s%N)
echo "$LABEL,ALL,1,pipeline,$(( (end - start) / 1000000 ))" >> "$OUT"

# Compare: median of warm rows, the cold row, and the pipeline row per label.
# Run on hardware close to your CI agents, not a fast-core laptop.

A timing script that bypasses the Nx cache, records cold and warm wall time for one project's test target, and records whole-workspace pipeline time as a separate row so Jest and Vitest runs at the same commit can be compared.

Which backend compatibility issues should you check before migrating?

…assuming the numbers carry over. Before you spend time on a pilot, rule out the blockers below. Any one of them can stall a migration or cancel the speed gain.

  • CommonJS-only dependencies. Vitest is built around ESM, while most Jest backend setups compile to CommonJS. Packages that ship only CJS, rely on require side effects, or are mocked with jest.mock hoisting can behave differently under ESM interop. The most common failures involve default-export shape mismatches and mocks that no longer intercept the module. Test your most heavily mocked modules first.
  • Decorators and emitDecoratorMetadata. DI frameworks such as NestJS and TypeORM read the design-time type metadata that TypeScript emits. esbuild does not emit that metadata, so injection fails at runtime. You will need a different transform, typically an SWC-based plugin. That transform is slower than esbuild, so measure again after adding it.
  • Thread pools. Worker threads share one process. Native addons, process.chdir, signal handlers, and code that expects its own process can crash or interfere with each other in that setting. Process forks are slower to start but are much closer to how Jest isolates tests.
  • Reduced isolation. If you turn off per-file isolation to gain speed, state persists across files. This includes module-level singletons, open DB pools, and mutated process.env. The result is order-dependent failures.
  • Database and network setup. Global setup runs outside the test context in both runners, but the two differ in how values reach tests and when teardown fires. Check that containers, migrations, and port allocation still behave correctly when many workers run at once.
// apps/orders-api/vitest.config.ts
import { defineConfig } from 'vitest/config';
import swc from 'unplugin-swc';

export default defineConfig({
  // esbuild does not emit decorator metadata, so DI breaks.
  // SWC emits it, but it is slower, so re-measure after adding it.
  plugins: [swc.vite({ module: { type: 'es6' } })],
  test: {
    environment: 'node',
    // Forks give each worker its own process, which is safer for
    // native addons, process.chdir and signal handlers than threads.
    pool: 'forks',
    // Keep per-file isolation on so singletons, DB pools and module state
    // do not leak between files. Turn it off only after a pilot proves it is safe.
    isolate: true,
    // Undo vi.stubEnv() and mocks after each test to limit order-dependent failures.
    unstubEnvs: true,
    restoreMocks: true,
    // Runs once, outside the test context, before any worker starts.
    globalSetup: ['./test/global-setup.ts'],
  },
});

// apps/orders-api/test/global-setup.ts
// Unlike Jest, values do not reach tests through globalThis. Pass them
// with provide() and read them in tests with inject('dbUrl').
export default async function setup(project: {
  provide: (key: string, value: unknown) => void;
}) {
  const dbUrl = 'postgres://test:test@localhost:55432/orders_test';
  // Start the container and run migrations here, once for all workers.
  project.provide('dbUrl', dbUrl);

  // The returned function runs as global teardown after all workers finish.
  return async () => {
    // Stop the container and release ports here.
  };
}

A Vitest config for an Nx backend project that swaps esbuild for SWC to emit decorator metadata, uses the forks pool with isolation kept on, resets stubbed env vars between tests, and passes database settings from global setup to tests through provide/inject rather than shared globals.

How do you migrate an Nx project from Jest to Vitest?

Those behaviours depend on the pool and isolation settings, so start the migration there.

Use Nx's Vitest support to generate a Vitest configuration and test target for the project, then delete jest.config.ts and the Jest-specific tsconfig. Generator names and options have moved between packages across Nx releases, so check them against your installed version rather than copying commands from older posts. Path aliases from tsconfig.base.json are not resolved automatically. Add Nx's tsconfig-paths Vite plugin, or an equivalent, to the config. Otherwise imports of other libraries fail at runtime even though the editor resolves them.

For backend suites, the forks pool is the safer choice. Child processes tolerate native modules and code that calls process.exit better than worker threads do. Keep isolate enabled at first, because turning it off lets module state leak between files. Disable it only after the suite passes consistently, and measure the gain before keeping the change. Prefer explicit imports from vitest over globals: true. They make each file's dependencies visible and avoid type clashes with leftover @types/jest.

Most APIs map directly:

  • jest.fn, jest.spyOn and jest.mock become vi.fn, vi.spyOn and vi.mock.
  • Fake timers move to vi.useFakeTimers.
  • jest.requireActual becomes await vi.importActual, which is asynchronous, so the mock factory must be async.

vi.mock is hoisted above imports. Any variable a factory references must be declared with vi.hoisted.

Partial mocks need the most care. A factory that omits an export makes Vitest throw when that export is accessed, where Jest would return undefined. ES module default exports also need an explicit default key in the factory. Calling vi.mock without a factory automocks the module or loads its __mocks__ file, which can replace real behaviour without any visible error. Review each converted mock against the original before trusting a green run.

// libs/orders-service/vite.config.ts (replaces jest.config.ts)
import { defineConfig } from 'vitest/config';
// Resolves tsconfig.base.json path aliases (@acme/*) at runtime.
// Check the import path against your installed @nx/vite version.
import { nxViteTsPaths } from '@nx/vite/plugins/nx-tsconfig-paths.plugin';

export default defineConfig({
  root: __dirname,
  cacheDir: '../../node_modules/.vite/libs/orders-service',
  plugins: [nxViteTsPaths()],
  test: {
    name: 'orders-service',
    environment: 'node',
    include: ['src/**/*.{test,spec}.ts'],
    // Explicit `import { vi, describe, it } from 'vitest'` in each file;
    // avoids type clashes with any leftover @types/jest.
    globals: false,
    // Child processes cope better than worker threads with native
    // modules and code that calls process.exit.
    pool: 'forks',
    // Fresh module registry per test file. Turn off only after the suite
    // passes consistently, and measure the speed gain before keeping it.
    isolate: true,
    // Restore spies created with vi.spyOn after each test, so leftover
    // mocks do not leak between tests in the same file.
    restoreMocks: true,
    watch: false,
    coverage: {
      provider: 'v8',
      reportsDirectory: '../../coverage/libs/orders-service',
    },
  },
});

A minimal Vitest config for an Nx backend library that resolves workspace path aliases, runs tests in the forks pool with per-file isolation, and uses explicit imports instead of globals.

How do you keep type safety when the test transform skips type-checking?

Vitest hands TypeScript to esbuild, and @swc/jest does the same with SWC. Both remove type annotations file by file and never build a full type graph. ts-jest with default settings works differently: it reports type errors as test failures. Teams on ts-jest often rely on that without noticing. After the switch, a test file that passes the wrong argument shape to a service still runs, and if the runtime values happen to work, it passes. If no other step in your pipeline type-checks spec files, those errors now merge into main.

Make type-checking its own target

Add a typecheck target to each project that runs tsc --noEmit against both the library tsconfig and the spec tsconfig. Spec files are often excluded from the build config, so checking only the library tsconfig leaves them unchecked. Mark the target cacheable in targetDefaults. Set its inputs to the project's source files, its tsconfig files, and the outputs of its dependencies. Leave out test runner configuration, because a change to the Vitest config should not invalidate the type-check cache. Then run nx affected -t test typecheck, and Nx schedules both targets in parallel across available workers.

The split pays off in two places. Locally, vitest --watch reruns in the time it takes to transform the changed files, without waiting for the compiler. Your editor's language server already shows type errors as you type. In CI, the costs separate. With ts-jest, each Jest worker type-checks the files it loads, so shared types are checked again in every worker and every project. With a separate target, each project runs tsc once, and Nx reuses the cached result until the project's own type inputs change.

When should you migrate, stay on Jest, or choose an alternative?

Migration pays off where transform and startup cost dominate. Workspaces with many small backend projects that frequently miss the cache benefit most, because Vitest's lighter per-file transform is paid on every miss. ESM-first codebases avoid Jest's module-system workarounds, and teams already using Vite can reuse resolution and plugin config.

Stay on Jest when the gains are unlikely to cover the cost. NestJS-style code that relies on emitted decorator metadata needs extra transform setup under Vitest. CJS-only dependencies can break or need inlining. If most CI runs are cache hits, or affected scopes are already narrow, runner speed rarely sets your wall-clock time.

Coexistence has a cost of its own. You maintain two configs, two sets of setup files, and coverage reports that don't merge cleanly. Contributors also have to remember which mocking API applies to each project.

Option Effort Expected impact Risk
Migrate to Vitest High High on cache misses Compatibility gaps
SWC transformer for Jest Low Medium–high Decorator config
Disable type-checking in ts-jest Very low Medium Needs separate tsc target
Tune workers Low Low–medium Memory pressure
Improve Nx or remote caching Medium High on repeat runs Cache correctness
Split large projects Medium–high Medium Boundary churn

Start incrementally. Migrate two or three representative projects, including one with decorators and one with heavy mocking. Then compare cache-miss timings and flake rates across several CI runs, and make the decision from that data rather than from expectations.

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 vitest vs jest, 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.