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 need | Version / notes |
|---|---|
| Node.js | Current LTS release |
| A Node.js project | ES modules recommended ("type": "module") |
3. Local setup
1Install Mocha and Chai
Chai 5 is ES-module only, so use
importsyntax.BASHnpm install --save-dev mocha chai npm pkg set type=module npm pkg set scripts.test="mocha"2Configure Mocha
A
.mocharc.jsontells Mocha where tests are and sets defaults..mocharc.json{ "spec": "test/**/*.test.js", "timeout": 5000, "recursive": true }
4. Create & run a project
1Write tests with hooks
beforeEachprepares 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); }); });2Test async code
Return a promise or use
asyncfunctions – Mocha waits for them.JSit('loads a user', async () => { const user = await loadUser(1); expect(user).to.have.property('name'); });3Stub dependencies with Sinon
Replace a function, check how it was called, and restore it.
JSnpm 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); });4Run
Use
--watchwhile developing.BASHnpm 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.
NODE_ENV=test
DATABASE_URL=postgres://test:test@localhost:5432/app_testKey dependencies
| Package / tool | Used for |
|---|---|
mocha | Test runner, describe/it, hooks, reporters |
chai | Assertions (expect, should, assert) |
sinon | Spies, stubs, mocks, fake timers |
supertest | HTTP API tests |
c8 | Coverage using Node’s built-in V8 coverage |
mocha-junit-reporter | JUnit XML for CI |
Folder structure
project/
├── src/
│ └── cart.js
├── test/
│ ├── cart.test.js
│ └── api.test.js
├── .mocharc.json
└── package.jsonEssential commands
| Command | What it does |
|---|---|
npx mocha | Run tests |
npx mocha --watch | Re-run on changes |
npx mocha --grep "Cart" | Run matching tests |
npx c8 mocha | Coverage report |
npx mocha --reporter spec|dot|json | Change 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
| Requirement | Recommendation |
|---|---|
| CI runner | GitHub Actions / GitLab CI / Jenkins with the same Node.js version as development |
| Install | npm ci from the lockfile |
| Gate | Test job marked as a required check before merge/deploy |
| Reports | JUnit XML / HTML / coverage uploaded as artifacts |
Deployment steps
1Add coverage and a JUnit report
c8 enforces thresholds; the JUnit reporter produces XML for CI dashboards.
BASHnpm 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"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.ymlname: 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:ci3Use a real database in CI when needed
GitHub Actions can start a service container for integration tests.
YAMLservices: 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.
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
awaitasync work inside tests. - Restore all stubs after each test.
- Measure coverage in CI with c8.
- Use descriptive
describe/itnames that read like sentences.