Testing & Code Quality

Mocha Setup & Deployment Guide

Flexible Node.js test framework – pair Mocha with Chai and Sinon, test async code and APIs, add coverage with c8 and run it in CI.

Updated Official documentation ↗

1. Introduction & use cases

Mocha is a mature, flexible JavaScript test framework for Node.js (and browsers). It provides the runner and structure (describe, it, hooks like beforeEach), while you choose the other pieces: Chai for assertions, Sinon for spies/stubs/mocks, c8 for coverage.

This modular approach and its rich reporter options make Mocha popular for back-end projects and libraries. It supports ES modules natively.

Where it is used

  • Back-end unit and integration tests
  • Testing Node.js libraries and CLIs
  • API tests with supertest
  • Projects that want full control over assertion and mocking libraries

2. Prerequisites

You needVersion / notes
Node.jsCurrent LTS release
A Node.js projectES modules recommended ("type": "module")

3. Local setup

  1. 1Install Mocha and Chai

    Chai 5 is ES-module only, so use import syntax.

    BASH
    npm install --save-dev mocha chai
    npm pkg set type=module
    npm pkg set scripts.test="mocha"
  2. 2Configure Mocha

    A .mocharc.json tells Mocha where tests are and sets defaults.

    .mocharc.json
    {
      "spec": "test/**/*.test.js",
      "timeout": 5000,
      "recursive": true
    }

4. Create & run a project

  1. 1Write tests with hooks

    beforeEach prepares fresh data for every test.

    JS
    // src/cart.js
    export class Cart {
      constructor() { this.items = []; }
      add(name, price, qty = 1) { this.items.push({ name, price, qty }); }
      total() { return this.items.reduce((s, i) => s + i.price * i.qty, 0); }
    }
    
    // test/cart.test.js
    import { expect } from 'chai';
    import { Cart } from '../src/cart.js';
    
    describe('Cart', () => {
      let cart;
      beforeEach(() => { cart = new Cart(); });
    
      it('starts empty', () => {
        expect(cart.total()).to.equal(0);
      });
      it('sums price × quantity', () => {
        cart.add('Pen', 25, 2);
        cart.add('Book', 200);
        expect(cart.total()).to.equal(250);
      });
    });
  2. 2Test async code

    Return a promise or use async functions – Mocha waits for them.

    JS
    it('loads a user', async () => {
      const user = await loadUser(1);
      expect(user).to.have.property('name');
    });
  3. 3Stub dependencies with Sinon

    Replace a function, check how it was called, and restore it.

    JS
    npm install --save-dev sinon
    
    import sinon from 'sinon';
    import * as mailer from '../src/mailer.js';
    
    afterEach(() => sinon.restore());
    
    it('sends an email', async () => {
      const send = sinon.stub(mailer.client, 'send').resolves({ ok: true });
      await notify('a@example.com');
      expect(send.calledOnce).to.equal(true);
    });
  4. 4Run

    Use --watch while developing.

    BASH
    npm test
    npx mocha --watch

✅ When it works you should see output like Figure 1.

5. Development configuration

Environment variables

Load test settings explicitly, e.g. mocha --require dotenv/config with DOTENV_CONFIG_PATH=.env.test, or with Node’s --env-file via NODE_OPTIONS.

.env.test
NODE_ENV=test
DATABASE_URL=postgres://test:test@localhost:5432/app_test

Key dependencies

Package / toolUsed for
mochaTest runner, describe/it, hooks, reporters
chaiAssertions (expect, should, assert)
sinonSpies, stubs, mocks, fake timers
supertestHTTP API tests
c8Coverage using Node’s built-in V8 coverage
mocha-junit-reporterJUnit XML for CI

Folder structure

project structure
project/
├── src/
│   └── cart.js
├── test/
│   ├── cart.test.js
│   └── api.test.js
├── .mocharc.json
└── package.json

Essential commands

CommandWhat it does
npx mochaRun tests
npx mocha --watchRe-run on changes
npx mocha --grep "Cart"Run matching tests
npx c8 mochaCoverage report
npx mocha --reporter spec|dot|jsonChange output format

6. Production deployment

Test frameworks are not deployed to a production server – in production they act as a quality gate: they run automatically in CI on every push and pull request, publish reports, and block the deployment when a test fails.

Server & hosting requirements

RequirementRecommendation
CI runnerGitHub Actions / GitLab CI / Jenkins with the same Node.js version as development
Installnpm ci from the lockfile
GateTest job marked as a required check before merge/deploy
ReportsJUnit XML / HTML / coverage uploaded as artifacts

Deployment steps

  1. 1Add coverage and a JUnit report

    c8 enforces thresholds; the JUnit reporter produces XML for CI dashboards.

    BASH
    npm install --save-dev c8 mocha-junit-reporter
    npm pkg set scripts.test:ci="c8 --check-coverage --lines 80 mocha --reporter mocha-junit-reporter --reporter-options mochaFile=reports/junit.xml"
  2. 2Run the tests in CI on every push

    Tests protect production only if they run automatically. This GitHub Actions workflow installs dependencies and runs the suite on every push and pull request; mark the job as a required check in branch protection so failing code cannot be merged or deployed.

    .github/workflows/tests.yml
    name: tests
    on:
      push:
        branches: [main]
      pull_request:
    jobs:
      test:
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v4
          - uses: actions/setup-node@v4
            with:
              node-version: lts/*
              cache: npm
          - run: npm ci
          - run: npm run test:ci
  3. 3Use a real database in CI when needed

    GitHub Actions can start a service container for integration tests.

    YAML
        services:
          postgres:
            image: postgres:17
            env:
              POSTGRES_PASSWORD: test
              POSTGRES_DB: app_test
            ports: ['5432:5432']
            options: >-
              --health-cmd pg_isready --health-interval 5s --health-retries 10

🗺 The whole path from your code to the live site is drawn in the deployment diagram.

7. Images & screenshots

Illustrations drawn for this guide from the commands above. Product dashboards change often, so for screens such as cloud consoles follow the step text and the official documentation.

terminal$ npm test Cart ✔ starts empty ✔ sums price × quantity users ✔ loads a user (41ms) 3 passing (58ms)
Figure 1: terminal output of the sample Mocha project (section 4).
1describe/it + Chai2npm test locally3CI: c8 + mocha4JUnit report5Deploy if green
Figure 2: production deployment flow (section 6).
project/├── src/│ └── cart.js├── test/│ ├── cart.test.js│ └── api.test.js├── .mocharc.json└── package.json
Figure 3: project folder structure (section 5).

8. Common errors & solutions

Error: Timeout of 2000ms exceeded

An async test never finished (missing await/done()), or the operation is slow. Fix the promise or raise timeout in .mocharc.json.

Error [ERR_REQUIRE_ESM] with Chai

Chai 5 is ESM-only. Use import { expect } from 'chai' with "type": "module", or stay on Chai 4 for CommonJS.

No tests found

Check spec globs in .mocharc.json and the file naming (*.test.js).

Tests affect each other

Restore stubs (sinon.restore()) and reset data in hooks.

Process does not exit after tests

Close servers/DB connections in after() or use --exit only as a last resort.

Best practices

  • Keep tests independent; use hooks for setup/cleanup.
  • Always await async work inside tests.
  • Restore all stubs after each test.
  • Measure coverage in CI with c8.
  • Use descriptive describe/it names that read like sentences.