Skip to content

Vitest

Vitest is a JavaScript test runner built on the Vite build tool that finds a project’s test files, runs them, and reports which assertions passed or failed. It reads the project’s existing vite.config.js, so tests go through the same plugins and module resolution as the app, and ES modules and TypeScript work without extra setup.

Its expect() assertions, snapshots, and mock functions follow the API of Jest, so many Jest test suites move to Vitest with few changes.

Installation and Setup

A project installs Vitest as a dev dependency:

Language: Shell
$ npm install --save-dev vitest

Vitest 5 needs Node.js 22.12 or later and Vite 6.4 or later. npm installs a compatible Vite version automatically. The --version flag prints the installed version:

Language: Shell
$ npx vitest --version
vitest/5.1.0 linux-x64 node-v26.13.0

Key Features

  • Finds test files automatically by their .test.js or .spec.js suffix, including TypeScript variants.
  • Exports test(), describe(), and expect() from the vitest package instead of defining globals by default.
  • Creates mock functions with vi.fn() and replaces whole modules with vi.mock().
  • Reruns only the tests affected by a changed file in watch mode, using Vite’s module graph.
  • Reports code coverage with the --coverage flag through the optional @vitest/coverage-v8 package.

Usage

Say a shop’s cart.js module exports a cartTotal() function. A file named cart.test.js imports the test helpers and checks the function with two tests:

Language: JavaScript
import { describe, expect, test } from "vitest";
import { cartTotal } from "./cart.js";

describe("cartTotal()", () => {
  test("adds up price times quantity", () => {
    const items = [
      { price: 5, quantity: 2 },
      { price: 12.5, quantity: 1 },
    ];
    expect(cartTotal(items)).toBe(22.5);
  });

  test("returns 0 for an empty cart", () => {
    expect(cartTotal([])).toBe(0);
  });
});

The run command runs every test file once and prints a summary:

Language: Shell
$ npx vitest run

 RUN  v5.1.0 /home/user/shop

 Test Files  1 passed (1)
      Tests  2 passed (2)
   Start at  09:41:07
   Duration  255ms (transform 51%, import 31%, worker 11%, tests 7%)

Without run, the vitest command starts watch mode in an interactive terminal and reruns the related tests on every save. In CI or any other non-interactive shell, it runs the tests once instead:

Language: Shell
$ npx vitest

To run only the tests whose names match a pattern, pass -t:

Language: Shell
$ npx vitest run -t "empty cart"

Most projects add a test script to package.json, so npm test starts Vitest:

Language: JSON
{
  "scripts": {
    "test": "vitest"
  }
}

For the full list of matchers and command-line options, see the Vitest documentation.

Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.


By Leodanis Pozo Ramos • Updated Nov. 6, 2026