Mocha
02 / 02

Configuration & Advanced Patterns

Configuration & Advanced Patterns

.mocharc.yml

# .mocharc.yml
spec: 'test/**/*.spec.js'
timeout: 5000
reporter: spec
require:
  - ts-node/register     # TypeScript support with no separate build step
  - test/setup.js        # global test setup (e.g. chai plugins)
ui: bdd                  # 'bdd' (describe/it) or 'tdd' (suite/test) — equivalent, pick a style
exit: false               # prefer fixing open handles over forcing --exit

Root Hooks (Global Setup)

// test/setup.js — loaded via --require, runs once for the whole test run
exports.mochaHooks = {
  beforeAll(done) {
    startTestDatabase().then(() => done());
  },
  afterAll(done) {
    stopTestDatabase().then(() => done());
  },
};
// Convenient for truly global setup, but couples every test file to this
// shared state — makes running a single file in isolation less reliable.

Parallel Mode

npx mocha --parallel --jobs 4

# Runs test FILES across separate worker processes. Requires tests to be
# genuinely independent — a shared mutable resource (a fixed port, a shared
# DB row, a global counter) that happened to work under serial execution
# can race and fail intermittently once parallelized.

CI Reporting

{
  "scripts": {
    "test": "mocha",
    "test:ci": "mocha --reporter mocha-junit-reporter --reporter-options mochaFile=./results/junit.xml"
  }
}

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free