Skip to content
Tutorials Center
My learning

Topics

Lesson 105 of 133 ยท Testing

Testing with Jest, Mocha and Chai

Learn how Jest and Mocha with Chai structure tests, what describe, it, expect, hooks and mock functions do, and map them to node:test with a runnable mini test framework.

The built-in test runner is a good default for new projects, but most existing Node.js code bases are tested with one of two older tools, and job descriptions still name them. Jest is an all-in-one framework: runner, assertions, mocks, snapshots and coverage in a single package. Mocha is only a runner; you pair it with an assertion library such as Chai and, when you need spies and stubs, Sinon (see Supertest and Sinon).

Both look nearly identical on the page: describe groups tests, it defines one, hooks prepare and clean up. If you understand that structure, you can read any of these suites, and moving between them is mostly a matter of vocabulary.

Neither package can be installed in our editor, so real configuration is shown read-only. To make the ideas runnable, this lesson builds a mini-Jest in about seventy lines and runs a test suite on it. Seeing how describe, beforeEach, expect(...).toBe and jest.fn() work inside makes the real tools much less mysterious.

The shape of a test file

A test has three steps, often called arrange, act, assert: set up the data, call the code, check the result. A suite groups tests that share a subject, and hooks run code around them.

JavaScript
// cart.test.js (Jest syntax)
import { Cart } from './cart.js';

describe('Cart', () => {
  let cart;
  beforeEach(() => {
    cart = new Cart();                      // a fresh cart for every test
  });

  it('starts empty', () => {
    expect(cart.total()).toBe(0);
  });

  it('adds up item prices', () => {
    cart.add({ name: 'pen', price: 3 }, 2);
    expect(cart.total()).toBe(6);
  });
});

Four rules make suites trustworthy: each test is independent (no test relies on another having run), each creates its own state in beforeEach, each checks one behaviour, and the name says what that behaviour is.

A mini-Jest you can run

This framework collects tests from describe and it, runs hooks around each one, supports expect with a few matchers (including .not and .rejects), and offers jest.fn() for recording calls. Below the framework is an ordinary-looking test file, including one test that fails on purpose so you can see a failure message.

Node.js A mini-Jest running a real-looking test file

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The structure to take away: the describe calls only register tests, and a runner later executes them in order, running every enclosing beforeEach first. That is why each test gets a fresh cart and mailer. A failing expect throws, the runner catches it, prints the message and carries on with the next test, exactly as Jest does. What real Jest adds is polish: a colourful diff in the message, parallel test files in worker processes, watch mode, and many more matchers.

Jest in a real project

Terminal
npm install --save-dev jest
JSON
{
  "scripts": { "test": "jest", "test:watch": "jest --watch", "coverage": "jest --coverage" }
}

Features that make people choose Jest:

  • jest.fn(), jest.spyOn(obj, 'method') record calls and can replace behaviour; mockResolvedValue(x) makes an async stub in one line.
  • jest.mock('./mailer.js') replaces a whole module in every file that imports it. Convenient, but magic: it is hoisted above imports by a code transform. That transform is also the main reason Jest's support for native ES modules is awkward (it needs --experimental-vm-modules, and mocking ESM works differently).
  • Fake timers (jest.useFakeTimers()) control setTimeout and Date; compare Mocking and Fake Timers.
  • Snapshots (expect(value).toMatchSnapshot()) store a serialized value in a file and fail when it changes. Useful for stable, small output; harmful when they are huge and people approve updates without reading them.
  • Coverage (--coverage) reports which lines and branches ran. Treat it as a map of untested code, not a score to maximize.

Mocha and Chai

Mocha provides describe, it and hooks (before, after, beforeEach, afterEach) and nothing else, so you choose the rest. Chai supplies three assertion styles; the expect style reads like a sentence.

JavaScript
import { expect } from 'chai';
import { Cart } from '../src/cart.js';

describe('Cart', function () {
  let cart;
  beforeEach(() => { cart = new Cart(); });

  it('adds up prices', () => {
    cart.add({ name: 'pen', price: 3 }, 2);
    expect(cart.total()).to.equal(6);
  });

  it('keeps the items', () => {
    cart.add({ name: 'pen', price: 3 });
    expect(cart.items).to.deep.equal([{ name: 'pen', price: 3, quantity: 1 }]);
  });

  it('rejects bad quantities', () => {
    expect(() => cart.add({ name: 'pen', price: 3 }, 0)).to.throw('positive');
  });
});
Terminal
npm install --save-dev mocha chai
npx mocha "test/**/*.test.js"

Mocha keeps its history of flexibility: it works with ESM and CommonJS, you can use any assertion library (even Node's assert), and it callbacks can return promises or take a done callback. A classic Mocha pitfall: arrow functions break this.timeout(5000), so tests that need a custom timeout use function () {}.

The same vocabulary everywhere

Idea Jest Mocha + Chai node:test
Group tests describe describe describe
One test it / test it it / test
Hooks beforeEach afterAll ... beforeEach after ... beforeEach after ...
Equal values expect(a).toBe(b) expect(a).to.equal(b) assert.equal(a, b)
Deep equal toEqual to.deep.equal assert.deepEqual
Throws toThrow to.throw assert.throws
Mock function jest.fn() sinon.stub() mock.fn()
Coverage --coverage nyc / c8 --experimental-test-coverage

Here is the Cart suite written for the built-in runner. This uses real node:test through the same helper as in the earlier lesson.

Node.js The same suite on node:test

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Every Jest idiom has a direct counterpart, which is why a migration is usually mechanical: replace expect(...).toX with assert, jest.fn with mock.fn, and drop the config file.

Which one should you pick?

  • New project, plain Node or a small service: node:test. No dependencies, ESM works, fast start-up.
  • Existing Jest suite, or a React front end: stay with Jest, or move to Vitest, which keeps Jest's API but runs on native ESM and TypeScript with much less configuration.
  • Existing Mocha suite: keep it. Mocha is stable and flexible, and Chai plus Sinon cover everything.
  • Whatever you pick: write tests that run in milliseconds, need no network, and do not depend on each other. Everything else is syntax.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In the mini-Jest, why does each test get a fresh cart?

    describe and it only register tests. The runner later runs the beforeEach hooks of every enclosing suite before each test, so state is rebuilt every time.
  2. 2. Which pair is the Chai-style equivalent of Jest's expect(a).toEqual(b)?

    toEqual compares objects by structure, which Chai calls deep equality. to.equal uses strict identity, like toBe.
  3. 3. What is the main reason Jest's jest.mock() complicates native ES modules?

    Jest rewrites files so jest.mock runs before require calls. Static ESM imports are resolved before any code runs, so mocking needs a different mechanism.
  4. 4. Mocha needs a separate library for assertions. Which one is NOT an option?

    describe is part of Mocha's test structure, not an assertion library. Chai, assert and should.js all provide assertions.

Summary

  • Jest bundles runner, assertions, mocks, snapshots and coverage; Mocha is a runner you pair with Chai (assertions) and Sinon (spies and stubs).
  • describe registers a group, it registers a test, and hooks run around each test; tests must be independent and fast.
  • expect(x).toBe(y) (Jest), expect(x).to.equal(y) (Chai) and assert.equal(x, y) (node:test) are the same idea in three dialects.
  • Mocks record calls (jest.fn(), sinon.stub(), mock.fn()); module mocking and snapshots are powerful and easy to overuse.
  • For new Node projects the built-in runner is enough; for existing suites, keep the tool you have, or consider Vitest as a modern Jest-compatible choice.

Next: Supertest and Sinon for HTTP and Stubs.