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

Quick reference

Mocha.js BDD Cheatsheet

A quick reference guide for Mocha.js: BDD test suite interface, describe, it, hooks, asynchronous tests, and Chai assertions.

· Published

Mocha is a feature-rich JavaScript test framework running on Node.js and in the browser, making asynchronous testing simple and fun.

BDD Interface

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

describe('User Authentication', () => {
  before(() => {
    // Runs once before all tests in this block
  });

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

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

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

  it('should authenticate user with valid credentials', () => {
    const user = authenticate('[email protected]', 'secret');
    expect(user).to.be.an('object');
    expect(user.token).to.be.a('string');
  });

  it.skip('temporarily skipped test', () => {
    // Skips execution
  });
});

Asynchronous Tests

Promises & Async/Await

it('should fetch user profile from API', async () => {
  const profile = await fetchProfile(101);
  expect(profile.name).to.equal('Alice');
});

Callbacks with done()

it('should save document via callback', (done) => {
  document.save((err) => {
    if (err) return done(err);
    done();
  });
});

Chai Assertions Quick Guide

// Should style
chai.should();
user.should.have.property('name').equal('Alice');
list.should.have.lengthOf(3);

// Expect style
expect(user).to.be.an('object');
expect(list).to.include(42);

References

Related topics