Mocha Basics

Mocha test framework essentials and syntax.

Test Structure

Basic test
describe("Array", function() {
  describe("#indexOf()", function() {
    it("should return -1", function() {
      assert.equal([1,2,3].indexOf(4), -1);
    });
  });
});

Arrow functions not recommended
it("test", () => {
  // this.timeout will not work
});

Running Tests

Run all tests
mocha

Specific file
mocha test/mytest.js

Watch mode
mocha --watch

Reporter
mocha --reporter spec
mocha --reporter json

Timeout
mocha --timeout 5000

Async Tests

Using done callback
it("async test", function(done) {
  setTimeout(() => {
    assert.equal(1, 1);
    done();
  }, 100);
});

Promises
it("promise test", function() {
  return Promise.resolve(42).then(val => {
    assert.equal(val, 42);
  });
});

Async/await
it("async/await", async function() {
  const result = await fetchData();
  assert.equal(result, "data");
});

Exclusive & Inclusive

Only run this test
it.only("only this", function() {});

Skip test
it.skip("skip this", function() {});

Pending test
it("pending test");

Only this suite
describe.only("only suite", function() {});