This page is not available in every language. Missing translations are disabled in the language selector.

Quick reference

Mocha.js TDD Cheatsheet

A quick reference guide for Mocha.js TDD interface: suite, test, setup, teardown hooks, async testing, and Chai expect assertions.

· Published

Mocha provides multiple testing interfaces. While bdd uses describe() and it(), the tdd interface uses classic xUnit-style suite() and test() conventions.

TDD Interface Setup

const { expect } = require('chai');

// Configure Mocha to use TDD interface
mocha.setup('tdd');

suite('Payment Processing', () => {
  suiteSetup(() => {
    // Runs once before all tests in this suite
  });

  suiteTeardown(() => {
    // Runs once after all tests in this suite
  });

  setup(() => {
    // Runs before each test
  });

  teardown(() => {
    // Runs after each test
  });

  test('validates card expiration date', () => {
    const isValid = validateExpiry('12/28');
    expect(isValid).to.be.true;
  });

  test('handles async network payments', async () => {
    const receipt = await chargeCard(100);
    expect(receipt.status).to.equal('success');
  });
});

Comparison: BDD vs TDD

Concept BDD Interface (bdd) TDD Interface (tdd)
Test Group describe("name", () => {}) suite("name", () => {})
Individual Test it("does something", () => {}) test("does something", () => {})
Before All Hook before(() => {}) suiteSetup(() => {})
After All Hook after(() => {}) suiteTeardown(() => {})
Before Each Hook beforeEach(() => {}) setup(() => {})
After Each Hook afterEach(() => {}) teardown(() => {})

Running TDD Tests via CLI

By default, the Mocha CLI uses the BDD interface. To run TDD test suites, supply --ui tdd:

mocha --ui tdd test/tdd/*.test.js

References

Related topics