Testing with Vitest and Jest

Intermediate · 10 min

How Vitest and Jest differ for Node code, covering ESM support, mocks, snapshots and fake timers, and when each is worth choosing over node:test.

Before thisThe built-in test runner

Devsplainers · 10 min

Testing with Vitest and Jest

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by DevsplainersReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Jest and Vitest share a familiar API: `describe`, `it`, `expect`, `toEqual`, spies, snapshots and fake timers. Code written for one ports to the other with small changes.
  • The main difference is the module pipeline. Vitest runs on Vite's transform and handles ESM and TypeScript out of the box. Jest was built for CommonJS, so native ESM needs `NODE_OPTIONS=--experimental-vm-modules` and `jest.unstable_mockModule`, or a transform step.
  • In Vitest `vi.mock('./mailer.js', factory)` is hoisted above your imports, so the module is replaced before anything imports it. In Jest ESM you must mock first and then `await import()` the code under test.
  • `vitest` starts in watch mode in a terminal and `vitest run` runs once, which is what CI needs. Both have built-in coverage, with Vitest using V8 coverage by default.
  • Snapshots (`toMatchSnapshot`, `toMatchInlineSnapshot`) record a value on first run and compare on later ones. They are cheap to write and easy to approve without looking, so keep them small.
  • Choose by project. Vitest suits new ESM or TypeScript projects. Jest suits large existing suites. `node:test` suits dependency-free libraries.

Why people reach past node:test

The built-in runner covers discovery, assertions, hooks, mocks, snapshots and coverage. Teams still use Jest and Vitest for reasons that are mostly about ergonomics: a richer expect matcher library (toHaveBeenCalledWith, toMatchObject, rejects), friendlier output and watch UIs, editor integration, and conveniences for mocking whole modules. If you have worked with Jest, Vitest feels almost identical, and that is by design.

Which one fits a Node project comes down to how your code is written. The video gives a four-round comparison (developer experience, performance, features and API, ecosystem). This lesson adds the part that bites in practice, which is modules.

Two runners, one familiar API

A test looks the same in both:

import { describe, it, expect, vi } from 'vitest';
import { slugify } from './signup.js';

describe('slugify', () => {
  it('lowercases and hyphenates', () => {
    expect(slugify('  Hello World ')).toBe('hello-world');
  });
});

In Jest you get describe, it and expect as globals, so you skip that import line, and vi becomes jest. Vitest can also expose globals if you set globals: true, but explicit imports are the default and are friendlier to editors and TypeScript.

Running them differs in one detail that matters in CI. vitest with no arguments watches files when it runs in a terminal. vitest run runs once and exits, which is what a pipeline wants. jest always runs once unless you pass --watch.

ESM is the real divider

Jest was built when Node was CommonJS. It transforms your files, normally with Babel, so that import becomes require. Modern Node projects with "type": "module" break that assumption, and I saw the result directly. On a fresh project with an ES module test file, Jest 30 failed with Must use import to load ES Module and suggested a transform, or Node 24.9+ with require(esm). The documented route for native ESM is an experimental flag:

NODE_OPTIONS=--experimental-vm-modules npx jest

That works, and prints an ExperimentalWarning, but it changes how mocking works. Vitest, built on Vite’s transform pipeline, loads ESM and TypeScript with no configuration. That, more than speed, is why new projects pick it. If your Node code is CommonJS, or you already have a Babel setup, Jest’s friction disappears.

Mocking a module

The classic need: test signup, which sends an email, without sending one.

// signup.js
import { send } from './mailer.js';
export async function signup(email) {
  await send(email, 'welcome');
  return { email, welcomed: true };
}

In Vitest:

import { describe, it, expect, vi } from 'vitest';
import { signup } from './signup.js';
import { send } from './mailer.js';

vi.mock('./mailer.js', () => ({ send: vi.fn().mockResolvedValue(undefined) }));

it('sends a welcome mail', async () => {
  const result = await signup('a@b.c');
  expect(send).toHaveBeenCalledWith('a@b.c', 'welcome');
  expect(result).toEqual({ email: 'a@b.c', welcomed: true });
});

vi.mock appears after the imports but is hoisted above them, so by the time signup.js loads, ./mailer.js is already the fake. The real mailer.js in my test threw an error to prove it was never called. The hoisting has a side effect: the factory cannot use variables declared elsewhere in the file, unless you create them with vi.hoisted.

In Jest with native ESM there is no automatic hoisting, so you mock first and import the code under test afterwards:

import { jest } from '@jest/globals';

jest.unstable_mockModule('./mailer.js', () => ({ send: jest.fn().mockResolvedValue(undefined) }));
const { signup } = await import('./signup.js');
const { send } = await import('./mailer.js');

The unstable_ prefix is real. It is the supported API, and its name says it can change. Both examples passed on my machine, on Vitest 5.1.1 and Jest 30.5.2. Mocking strategy more broadly, including the built-in mock object, is in mocking and test doubles in Node.

Snapshots and fake timers

Snapshots record a value the first time a test runs and compare against it afterwards:

expect(slugify('  Hello World ')).toMatchInlineSnapshot(`"hello-world"`);
expect(slugify('A B')).toMatchSnapshot(); // written to __snapshots__/

They are quick to write, which is both their strength and the trap. A large snapshot that nobody reads gets updated on every failure with -u, and then it protects nothing. Use them for small, stable outputs such as error messages or serialized structures, and read the diff before updating.

Fake timers let you test debouncing, retries and timeouts without waiting:

vi.useFakeTimers();
const cb = vi.fn();
setTimeout(cb, 1000);
vi.advanceTimersByTime(1000);
expect(cb).toHaveBeenCalledOnce();
vi.useRealTimers();

Jest’s equivalent is jest.useFakeTimers() and jest.advanceTimersByTime().

Choosing

  • Vitest: new ESM or TypeScript projects, or any project already on Vite. Fast, little config.
  • Jest: large existing suites, CommonJS code, projects tied to Jest-specific tooling.
  • node:test: libraries and small services where you would rather have no test dependencies.

Moving between them is mostly find-and-replace on jest and vi, plus config. The decision matters less than writing good tests, and the testing strategy in frontend testing strategies applies on the server too.

What the video covers

Devsplainers’ ten-minute animated comparison is chaptered: the pipeline problem, what testing frameworks solve, then four rounds (developer experience, performance, features and API, ecosystem and community), when to pick Vitest versus Jest, and a verdict. It was published in April 2026, so its recommendations are current. It is a conceptual comparison with little code, from a smaller channel with around 24,000 subscribers, and its transcript was not available. The ESM behaviour, module mocking, snapshot and timer examples above are carried by the prose, and I ran each of them. The “go deeper” link from Web Dev Simplified is a 2022 hands-on Vitest demo that predates Vitest 1.0.

Where this fits

A runner executes your tests. For a Node service, the most valuable tests exercise HTTP routes, which is testing HTTP APIs with Supertest.

Check yourself

  1. 01Your Jest test imports an ES module and fails with `Must use import to load ES Module`. What are your options?

    Run Jest with `NODE_OPTIONS=--experimental-vm-modules` so it can load native ESM, add a transform such as babel-jest to compile to CommonJS, or move to a runner that handles ESM directly, such as Vitest. The experimental flag also changes how you mock modules, using `jest.unstable_mockModule` instead of `jest.mock`.

  2. 02Why can you call `vi.mock` after your `import` lines in Vitest and still have the mock apply?

    Vitest hoists `vi.mock` calls to the top of the file before the imports run, so the module registry already holds your replacement when `./signup.js` imports `./mailer.js`. Because of hoisting, the factory cannot reference variables declared in the file unless they are created with `vi.hoisted`.

  3. 03A snapshot test fails after a refactor and the output looks fine. What should you do before updating the snapshot?

    Read the diff and decide whether the change was intended. Only then rerun with the update flag (`vitest -u` or `jest -u`). Blindly updating turns the snapshot into a rubber stamp that no longer catches regressions. Small, focused snapshots or explicit `expect` assertions make this review easier.

  4. 04When is the built-in `node:test` runner a better choice than Vitest or Jest?

    When you want zero dependencies, such as a library, a CLI or a small service, and the built-in assertions, mocks, snapshots and coverage are enough. It starts fast and has nothing to upgrade. Vitest and Jest earn their weight when you want richer matchers, module mocking conveniences, a UI or IDE integration, or you already have a large suite on one of them.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark