DEV Community

Cover image for Migrate Jest to Vitest: move TypeScript tests
Sascha Mirow-Stanitzok
Sascha Mirow-Stanitzok

Posted on Originally published at sascha-ms.de

Migrate Jest to Vitest: move TypeScript tests

To migrate Jest to Vitest sounds like one of those cleanup tickets that sit in the backlog for months. Since TypeScript 7, though, the ticket has a deadline of its own. Install the new compiler and the next npm test shows nothing but red test suites, because ts-jest needs the compiler’s programming interface and TypeScript 7 no longer ships it. In my article on the TypeScript 7 migration I named Vitest as one of two ways out. Today I’ll walk through that path in detail.

The example is a small, made-up loan service for a city library: two Lambda handlers in TypeScript, one DynamoDB call, a module mock and fake timers. That is exactly the mix you find in real Serverless projects. We’ll move the tests over step by step, let a small check script find the tricky spots, and look at the errors almost everyone runs into once. The source code of the Lambda functions stays unchanged.

In short

Vitest understands almost every Jest call once you replace jest with vi. It compiles TypeScript on its own, so it works without ts-jest and with TypeScript 7. The real work hides in a few places: module mocks with a default export, jest.requireActual, Jest types and matcher libraries. The most common stumbling block is a mock factory that does not return an object.

What you will learn in this article

  • Why ts-jest no longer starts with TypeScript 7 and which ways out exist
  • How a check script finds the Jest code that needs manual work
  • How to move module mocks, partial mocks and types over to Vitest
  • How aws-sdk-client-mock tests for Lambda handlers keep working
  • Which differences in mockReset, hooks and filters can surprise you

Why migrate Jest to Vitest right now?

Jest has served me well for many years. The API is familiar, the error messages are clear, and for Lambda handlers it does everything you need. The trouble is the road that leads there. Jest runs JavaScript. For TypeScript tests you need a transformer, and in many projects that is ts-jest. It compiles every test file with the TypeScript compiler, which it loads as a library.

That library is gone in TypeScript 7.0. The new compiler is written in Go and, for now, has no JavaScript interface. That is why ts-jest lists typescript >=4.3 <7 as a peer dependency. If you install TypeScript 7 anyway, npm only warns at first. Then the test run greets you with this:

FAIL test/ausleihe.test.ts
  ● Test suite failed to run

    The TypeScript compiler "typescript" (version 7.0.2) does not expose the
    JavaScript compiler API required by ts-jest. To use TypeScript 7 for project
    type-checking, install it as "@typescript/native" and alias
    "@typescript/typescript6" as "typescript" for ts-jest.
Enter fullscreen mode Exit fullscreen mode

The message even suggests a workaround: install TypeScript 6 side by side under an alias. That works, but it is a crutch you will have to remove later. Vitest, on the other hand, compiles TypeScript with the tooling from the Vite ecosystem (esbuild or Oxc) and does not check types while doing so. Type checking is the job of tsc --noEmit from TypeScript 7, which is a lot faster than it used to be.

Vitest or @swc/jest?

There is a second, smaller step: keep Jest and only swap ts-jest for @swc/jest. The current cdk init template does exactly that. Which route fits better depends on how much you want to touch.

Criterion Jest with @swc/jest Vitest
Migration effort very small, only the transformer small to medium, depending on the number of mocks
TypeScript 7 works, type checks separately with tsc works, type checks separately with tsc
ESM projects possible, but needs extra configuration works without extra steps
Watch mode Jest watch fast, only affected tests
Custom matchers and plugins large Jest ecosystem many packages have Vitest variants
Future depends on two projects one tool for compiling and testing

My advice before you migrate Jest to Vitest: for a repository with hundreds of test files and lots of Jest plugins, @swc/jest is the pragmatic first step. For typical Serverless projects with a manageable number of tests, the full switch pays off. You clean up once, and afterwards there is one tool less in your stack.

What stays the same and what changes

Good news first: describe, it, expect and almost all matchers have the same names and behave the same way. jest.fn() becomes vi.fn(), jest.spyOn() becomes vi.spyOn(), and jest.useFakeTimers() becomes vi.useFakeTimers(). Most of the work is therefore search and replace. You do need to watch out where Vitest deliberately works differently. I collected the most important cases in a table.

Jest Vitest What you need to do
Global functions without import no global mode by default import from vitest or set globals: true
jest.mock(path, () => value) sets the default export factory must return an object with all exports return { default: value }
jest.requireActual() vi.importActual() is asynchronous make the factory async or use importOriginal
Types such as jest.Mock, jest.MockedFunction no jest namespace Mock, vi.mocked() from vitest
mockReset() replaces the implementation with an empty function mockReset() restores the original implementation check tests that rely on undefined
done callback not supported rewrite the test with async/await
Hooks run one after another in order hooks run as a stack by default use sequence.hooks: "list" if needed
__mocks__ folder applies automatically applies only with vi.mock() add vi.mock() or move it into setupFiles
jest.setTimeout() vi.setConfig({ testTimeout }) replace

On top of that, Vitest 5 has a default that actually helps here: clearMocks is switched on out of the box. Before every test, the call history of all mocks is cleared. If you had clearMocks: true in Jest, you get the same behavior. If you did not, and a test accidentally relies on calls from the previous test, the switch uncovers a real bug in your tests.

🎬 Test run before and after: Jest with ts-jest compared to Vitest – this animated diagram only runs on my site: watch it on sascha-ms.de

Migrate Jest to Vitest step by step

Prerequisites

  • Node.js 22.12 or newer (required by Vitest 5, Node.js 24 works as well)
  • a project with Jest and ts-jest, here with Jest 30 and TypeScript 6
  • a clean Git state so you can commit every step on its own
  • about an hour for a small project, more if you have many module mocks

The sample project has three test files: leihfrist.test.ts with fake timers, ausleihe.test.ts with a mocked DynamoDB client and mahnlauf.test.ts with module mocks. Before the switch, all seven tests pass, and that is exactly the goal afterwards, too.

Step 1: Find the tricky spots automatically

Before you change anything, it pays to see where manual work is needed. The following script scans all test files for patterns that a simple replacement of jest with vi does not fix. It is deliberately simple and works line by line. So it does not replace reading the code, but it quickly shows you how big the job will be.

// scripts/jest-check.mjs
// Finds places in test files that need manual work when moving from Jest to Vitest.
// Usage: node scripts/jest-check.mjs test
import { readdirSync, readFileSync, statSync } from "node:fs";
import { join } from "node:path";

const RULES = [
  { pattern: /jest\.mock\([^,]+,\s*(async\s*)?\(\)\s*=>(?![\s(]*\{)/, hint: "factory does not return an object: return { default: … } in Vitest" },
  { pattern: /jest\.requireActual\(/, hint: "replace with await vi.importActual(…) or importOriginal(), make the factory async" },
  { pattern: /jest\.(Mock|MockedFunction|Mocked|SpyInstance)\b/, hint: "import types from 'vitest' (Mock, Mocked, MockInstance)" },
  { pattern: /jest\.setTimeout\(/, hint: "use vi.setConfig({ testTimeout }) or a timeout test option" },
  { pattern: /useFakeTimers\(\s*\{\s*legacyFakeTimers/, hint: "Vitest has no legacy timers" },
  { pattern: /jest\.replaceProperty\(/, hint: "use vi.stubEnv or vi.spyOn" },
  { pattern: /\b(it|test)\([^)]*\(\s*done\s*\)/, hint: "done callback: rewrite the test with async/await" },
  { pattern: /\.mockReset\(\)/, hint: "in Vitest, mockReset restores the original implementation" },
  { pattern: /JEST_WORKER_ID/, hint: "use VITEST_POOL_ID" },
  { pattern: /aws-sdk-client-mock-jest/, hint: "switch to aws-sdk-client-mock-vitest" },
];

function files(dir) {
  return readdirSync(dir).flatMap((name) => {
    const path = join(dir, name);
    if (name === "node_modules") return [];
    return statSync(path).isDirectory() ? files(path) : /\.(test|spec)\.[cm]?[jt]sx?$/.test(name) ? [path] : [];
  });
}

let hits = 0;
for (const file of files(process.argv[2] ?? ".")) {
  readFileSync(file, "utf8")
    .split("\n")
    .forEach((line, i) => {
      for (const { pattern, hint } of RULES) {
        if (pattern.test(line)) {
          hits++;
          console.log(file + ":" + (i + 1) + "  " + hint);
        }
      }
    });
}
console.log(hits === 0 ? "No manual work found." : "\n" + hits + " place(s) to check.");
process.exitCode = hits === 0 ? 0 : 1;
Enter fullscreen mode Exit fullscreen mode

In the sample project, the script reports four places. Everything else is plain renaming:

node scripts/jest-check.mjs test
Enter fullscreen mode Exit fullscreen mode
test/ausleihe.test.ts:6  switch to aws-sdk-client-mock-vitest
test/mahnlauf.test.ts:6  factory does not return an object: return { default: … } in Vitest
test/mahnlauf.test.ts:10  replace with await vi.importActual(…) or importOriginal(), make the factory async
test/mahnlauf.test.ts:14  import types from 'vitest' (Mock, Mocked, MockInstance)

4 place(s) to check.
Enter fullscreen mode Exit fullscreen mode

I set exit code 1 on purpose when the script finds something. That way you can add it to your CI pipeline after the switch, and nobody writes jest.requireActual into a new test out of habit.

Step 2: Swap the packages

Jest, ts-jest and the Jest types go. In their place you add Vitest, the coverage package and, if you mock AWS SDK calls, the Vitest flavor of the matchers. TypeScript can move to version 7 in the same go.

npm uninstall jest ts-jest @types/jest aws-sdk-client-mock-jest
npm install -D vitest@^5.1.0 @vitest/coverage-v8@^5.1.0 aws-sdk-client-mock-vitest@^8.0.0 typescript@^7.0.2
rm jest.config.js
Enter fullscreen mode Exit fullscreen mode

In Vitest 5, Vite itself is a peer dependency. npm installs it automatically; with Yarn you have to add vite as a dev dependency yourself. Pick the matching major version of aws-sdk-client-mock-vitest: version 8 belongs to Vitest 5, for Vitest 4 you need 7.x.

Step 3: Create vitest.config.ts and a setup file

A small Vitest configuration replaces the Jest one. roots becomes include, and collectCoverageFrom becomes coverage.include. You no longer need a transformer, because Vitest compiles TypeScript itself.

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

export default defineConfig({
  test: {
    environment: "node",
    include: ["test/**/*.test.ts"],
    setupFiles: ["test/setup.ts"],
    // Already the default in Vitest 5, spelled out here for clarity
    clearMocks: true,
    coverage: { provider: "v8", include: ["src/**/*.ts"] },
  },
});
Enter fullscreen mode Exit fullscreen mode

The setup file runs before every test file. This is where you register the matchers for the AWS SDK mock, for example, so that no test file has to import them on its own:

// test/setup.ts
// Registers toHaveReceivedCommandWith and friends for all tests
import "aws-sdk-client-mock-vitest/extend";
Enter fullscreen mode Exit fullscreen mode

Step 4: Adjust tsconfig.json

In tsconfig.json, "jest" disappears from types. Since the test functions are now imported, TypeScript no longer needs global types for them. And because tsc only checks and no longer emits anything, you set noEmit and can switch moduleResolution to bundler. The Lambda code is bundled by esbuild anyway, whether through the Serverless Framework v4 or the NodejsFunction in the AWS CDK.

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "esnext",
    "moduleResolution": "bundler",
    "strict": true,
    "skipLibCheck": true,
    "noEmit": true,
    "types": ["node"]
  },
  "include": ["src", "test", "vitest.config.ts"]
}
Enter fullscreen mode Exit fullscreen mode

Step 5: Imports instead of global functions

Jest provides describe, it, expect and jest as globals. Vitest can mimic that with globals: true, but I recommend explicit imports. Every file shows at a glance where a function comes from, and you need no global types. For files like the loan period test, that is actually the only change: one import line at the top, and jest. becomes vi..

// test/leihfrist.test.ts
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { berechneRueckgabe, istUeberfaellig } from "../src/leihfrist";

describe("leihfrist", () => {
  beforeEach(() => {
    vi.useFakeTimers();
    vi.setSystemTime(new Date("2026-11-13T10:00:00Z"));
  });
  afterEach(() => {
    vi.useRealTimers();
  });

  it("calculates a 28-day loan period", () => {
    expect(berechneRueckgabe(new Date()).toISOString()).toBe("2026-12-11T10:00:00.000Z");
  });

  it("detects overdue books", () => {
    expect(istUeberfaellig(new Date("2026-11-12T00:00:00Z"))).toBe(true);
    expect(istUeberfaellig(new Date("2026-11-14T00:00:00Z"))).toBe(false);
  });
});
Enter fullscreen mode Exit fullscreen mode

With many files, a search and replace in your IDE does most of the work. Replace jest. with vi. and add the import line. Afterwards, check with git diff that you did not also hit a string like "jest.config.js".

Step 6: Rework module mocks

This is where the actual work is. The reminder run calls a function that comes as the default export from erinnerung.ts, and it uses istUeberfaellig from the loan period module. In the Jest test it looked like this:

// test/mahnlauf.test.ts (before, Jest)
jest.mock("../src/erinnerung", () => jest.fn());

jest.mock("../src/leihfrist", () => ({
  ...jest.requireActual("../src/leihfrist"),
  istUeberfaellig: jest.fn((rueckgabe: Date) => rueckgabe.getUTCFullYear() < 2026),
}));

const erinnerung = sendeErinnerung as jest.MockedFunction<typeof sendeErinnerung>;
Enter fullscreen mode Exit fullscreen mode

Three things change. First, the factory for erinnerung.ts has to return an object with a default key, because Vitest does not treat the return value as the default export. Second, Vitest loads the real module asynchronously. The most convenient way is the importOriginal parameter that Vitest passes to the factory. Third, vi.mocked() replaces the type cast to jest.MockedFunction.

// test/mahnlauf.test.ts
import { beforeEach, describe, expect, it, vi } from "vitest";
import sendeErinnerung from "../src/erinnerung";
import { mahnlauf } from "../src/mahnlauf";

// Vitest: the factory returns an object with all exports, including the default export
vi.mock("../src/erinnerung", () => ({ default: vi.fn() }));

// Partial mock: importOriginal loads the real module asynchronously, so the factory is async
vi.mock("../src/leihfrist", async (importOriginal) => ({
  ...(await importOriginal<typeof import("../src/leihfrist")>()),
  istUeberfaellig: vi.fn((rueckgabe: Date) => rueckgabe.getUTCFullYear() < 2026),
}));

const erinnerung = vi.mocked(sendeErinnerung);

describe("mahnlauf", () => {
  // Curly braces: if a hook returns a function, Vitest calls it as a cleanup function
  beforeEach(() => {
    erinnerung.mockClear();
  });

  it("reminds only for overdue loans", async () => {
    const anzahl = await mahnlauf([
      { leserId: "l-1", titel: "The City of Clocks", rueckgabe: "2025-12-01T00:00:00Z" },
      { leserId: "l-2", titel: "Fog over Kiel", rueckgabe: "2026-12-24T00:00:00Z" },
    ]);
    expect(anzahl).toBe(1);
    expect(erinnerung).toHaveBeenCalledTimes(1);
    expect(erinnerung).toHaveBeenCalledWith("l-1", "The City of Clocks");
  });

  it("sends nothing when everything is on time", async () => {
    await mahnlauf([]);
    expect(erinnerung).not.toHaveBeenCalled();
  });
});
Enter fullscreen mode Exit fullscreen mode

Note the comment on beforeEach. The Jest version had beforeEach(() => erinnerung.mockClear()) without braces. That returns the mock, which is a function. Vitest treats a returned function as a cleanup step and calls it after the test. Nothing breaks, but it is an invisible extra call that will confuse you sooner or later when you count calls. Since Vitest 5, vi.mock calls also have to sit at the top level of the file. Nested calls inside a describe now throw an error. For conditional mocks there is vi.doMock.

Step 7: Test Lambda handlers with aws-sdk-client-mock

Good news for every Serverless project: aws-sdk-client-mock itself does not depend on the test runner and stays. Only the matchers such as toHaveReceivedCommandWith now come from aws-sdk-client-mock-vitest, and the setup file from step 3 already registers them. In the test file, the import of aws-sdk-client-mock-jest goes away and the Vitest import comes in. Everything else stays the same, line by line:

// test/ausleihe.test.ts
import { ConditionalCheckFailedException } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient, PutCommand } from "@aws-sdk/lib-dynamodb";
import type { APIGatewayProxyEventV2 } from "aws-lambda";
import { mockClient } from "aws-sdk-client-mock";
import { beforeEach, describe, expect, it } from "vitest";
import { handler } from "../src/ausleihe";

const ddbMock = mockClient(DynamoDBDocumentClient);
const anfrage = (body: object) => ({ body: JSON.stringify(body) }) as APIGatewayProxyEventV2;

describe("ausleihe", () => {
  beforeEach(() => {
    ddbMock.reset();
    process.env.TABELLE = "ausleihen";
  });

  it("creates a loan", async () => {
    ddbMock.on(PutCommand).resolves({});
    const antwort = await handler(anfrage({ buchId: "b-42", leserId: "l-7" }));
    expect(antwort).toMatchObject({ statusCode: 201 });
    expect(ddbMock).toHaveReceivedCommandWith(PutCommand, {
      TableName: "ausleihen",
      Item: expect.objectContaining({ pk: "BUCH#b-42", leserId: "l-7" }),
    });
  });

  it("returns 409 when the book is already on loan", async () => {
    ddbMock
      .on(PutCommand)
      .rejects(new ConditionalCheckFailedException({ message: "taken", $metadata: {} }));
    const antwort = await handler(anfrage({ buchId: "b-42", leserId: "l-7" }));
    expect(antwort).toMatchObject({ statusCode: 409 });
  });

  it("rejects incomplete requests", async () => {
    const antwort = await handler(anfrage({ buchId: "b-42" }));
    expect(antwort).toMatchObject({ statusCode: 400 });
    expect(ddbMock).not.toHaveReceivedCommand(PutCommand);
  });
});
Enter fullscreen mode Exit fullscreen mode

How to cut Lambda handlers so they are easy to test in the first place is covered in detail in Lambda unit tests with Vitest. This article picks up where Jest tests already exist.

Step 8: Set scripts and run everything

In package.json you separate testing from type checking. That matters, because Vitest does not check types. A test can therefore pass even though tsc finds an error.

{
  "scripts": {
    "test": "vitest run",
    "typecheck": "tsc --noEmit",
    "coverage": "vitest run --coverage",
    "check:jest": "node scripts/jest-check.mjs test"
  }
}
Enter fullscreen mode Exit fullscreen mode
npm run check:jest
npm run typecheck
npm test
Enter fullscreen mode Exit fullscreen mode

If everything fits, the check script reports “No manual work found.”, tsc stays quiet, and Vitest shows this result:

RUN  v5.1.0 /project/city-library

 Test Files  3 passed (3)
      Tests  7 passed (7)
   Duration  547ms
Enter fullscreen mode Exit fullscreen mode

Step 9: Update the CI pipeline

Little changes in the pipeline. What matters is that type checking becomes a step of its own instead of quietly disappearing. An example for GitHub Actions:

# .github/workflows/test.yml
name: test
on: [push, pull_request]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: npm
      - run: npm ci
      - run: npm run check:jest
      - run: npm run typecheck
      - run: npm test -- --coverage
Enter fullscreen mode Exit fullscreen mode

Common errors when moving from Jest to Vitest

“is not returning an object” in a module mock

This is the classic. If you leave vi.mock("../src/erinnerung", () => vi.fn()) the way it came from Jest, the test file does not even start. Vitest reports that the factory does not return an object and kindly asks whether you meant to return an object with a default key. That is exactly the fix.

Cannot find name 'describe' or 'jest'

This message comes from tsc, not from Vitest. Either a file is missing the import from vitest, or there is still a jest. somewhere. If you prefer globals: true, you also have to add "vitest/globals" to the types in tsconfig.json.

mockReset suddenly returns real values

In Jest, mockReset() replaces the implementation with an empty function that returns undefined. Vitest instead restores the original implementation, so for vi.fn(impl) you get impl back. Tests that expect undefined after a reset will then fail. Most of the time, mockClear() was what you meant anyway.

Tests with a done callback

Vitest does not support the done parameter. Rewrite these tests with async/await. If a callback API is involved, wrap the call in a Promise. Frankly, these tests are good candidates for a cleanup anyway, since a forgotten done call used to cause puzzling timeouts.

Hook order and test filters

By default, Vitest runs afterEach hooks in reverse order, like a stack. If your cleanup steps depend on each other, sequence: { hooks: "list" } restores the Jest behavior. Vitest also joins the full test name with " > ". A filter like -t "mahnlauf reminds" from old scripts therefore finds nothing, while -t "mahnlauf > reminds" does.

Coverage numbers differ

Jest measures coverage with Istanbul by default, while the example above uses the V8 provider of Vitest. The two count branches slightly differently. A jump of a few percentage points is therefore no sign of lost tests. If your pipeline has hard thresholds, measure again after the switch and adjust the values on purpose instead of quietly lowering them.

My take

I think the switch is one of those rare upgrades that clean up more than they cost. Jest has not gotten worse. But the chain of Jest, ts-jest, custom types and a compiler version that has to fit everything was already fragile before TypeScript 7. With Vitest, one tool compiles the code and runs the tests, and tsc takes care of the types. I like that clear division of labor, because it matches what esbuild already does when it bundles Lambda functions.

What I would push back on is the reflex to pack the whole thing into one big pull request with TypeScript 7, a Node update and new lint rules. If a test is red afterwards, you have no idea who is to blame. Do the switch in small commits: first the check script, then the packages, then file by file. And do not let any tests vanish in that pull request. The number of tests before and after the switch has to match, otherwise something is wrong.

One point to be honest with yourself about: if your repository leans heavily on Jest-specific plugins, say custom reporters, snapshot serializers or environments, check first whether Vitest counterparts exist. If they do not, @swc/jest is the better bridge. No team gains anything if the tests check less after the switch than before.

FAQ

Is Vitest faster than Jest?

In many TypeScript projects, yes, especially in watch mode, because Vitest only reruns the tests affected by a change. How big the difference is depends heavily on the project, though. Measure it on your own repository instead of trusting someone else’s benchmarks.

Can I run Jest tests in Vitest without changes?

Partly. With globals: true and a global alias from jest to vi, simple tests run right away. Module mocks with a default export, jest.requireActual and Jest types still need adjusting.

Do I need ts-jest or Babel for Vitest?

No. Vitest compiles TypeScript itself with the tooling from the Vite ecosystem. You need neither ts-jest nor Babel, only tsc for type checking.

Does aws-sdk-client-mock work with Vitest?

Yes. The aws-sdk-client-mock package is independent of the test runner. For the matchers such as toHaveReceivedCommandWith, use aws-sdk-client-mock-vitest in the major version that matches your Vitest version.

Your next step

Copy the check script into your project and run it once over your tests. The number at the end tells you whether the switch is an afternoon or a sprint. With a handful of hits, I would not wait long and just create the branch. I am curious: how many places did the script find in your code, and which Jest quirk cost you the most time?

All code from this article, ready to run: smirowstanitzok/sascha-ms-examples

Sources

This post was created with AI assistance.


👉 Next step: New here? My start page collects the best articles, tools and learning paths in one place.

📬 Stay updated: New articles on serverless, AI and leading tech teams via RSS, browser push or the weekly newsletter (in German).

Originally published on sascha-ms.de. More articles on serverless, AI in everyday development and leading tech teams: sascha-ms.de/en

Top comments (0)