Skip to content

Jest

Jest is a JavaScript test runner that finds a project’s test files, runs them in parallel, and reports which assertions passed or failed. It bundles the assertion library, mock functions, snapshot testing, and code coverage into one jest command, so a project needs no other testing packages to get started.

Meta donated Jest to the OpenJS Foundation in 2022. Vitest is a newer alternative with a largely compatible API.

Installation and Setup

A project installs Jest as a dev dependency:

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

Next, confirm the installed version:

Language: Shell
$ npx jest --version
30.5.2

Jest’s support for ES modules is still experimental, so a project that uses import in its tests starts Jest with the Node.js --experimental-vm-modules flag. Add a test script to package.json that does this:

Language: JSON
{
  "type": "module",
  "scripts": {
    "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js"
  }
}

Key Features

  • Finds test files automatically by their .test.js or .spec.js suffix or a __tests__ folder.
  • Ships test(), describe(), and expect() as globals, with matchers such as .toBe() and .toEqual().
  • Creates mock functions with jest.fn() to record calls and replace dependencies.
  • Records snapshot files that flag unexpected changes in rendered output or large objects.
  • Reports code coverage with the --coverage flag and no extra setup.

Usage

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

Language: JavaScript
import { cartTotal } from "./cart.js";

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);
});

Running the test script runs every test file and prints a summary:

Language: Shell
$ npm test
PASS ./cart.test.js
  ✓ adds up price times quantity (3 ms)
  ✓ returns 0 for an empty cart

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        0.28 s
Ran all test suites.

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

Language: Shell
$ npm test -- -t "empty cart"

To rerun the tests related to changed files on every save, start watch mode:

Language: Shell
$ npm test -- --watch

To add a coverage table for each source file, pass --coverage:

Language: Shell
$ npm test -- --coverage

For the full list of matchers and command-line options, see the Jest 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