Mocha Usage Tips

While the main Mocha.js website provides useful information, it's fairly verbose (that's really a good thing). Here are several tips to help newcomers understand some of the main features of Mocha.

Running commands before and after tests (i.e. Hooks)

Take advantage of Mocha's before, beforeEach, after and afterEach hooks to define commands to run for all of our tests. This helps reduce repetitious code.

"Hooks" Docs

Write Tests Faster

When writing new functional tests, it may take several tries to get it right. To avoid running the entire test suite for each iteration, use Mocha's only & skip test properties to fine tune which tests get run.

Do make sure to remove them before committing your code though.

Exclusive/Inclusive Test Docs

Async Tests

Due to the nature of some set ups, asyncronous actions are inevitable. To help with this, Mocha provides two ways of writing tests:

Use a 'done' callback

You must request a done argument from the it function, and then call it when the test has completed.

it("should track time", function(done) {
  var startTime = new Date();

  window.setTimeout(function() {
    var endTime = new Date();
    // this probably won't pass due to the setTimeout resolution not being entirely accurate
    // https://www.nczonline.net/blog/2011/12/14/timer-resolution-in-browsers/
    expect(endTime - startTime).to.equal(200);
    done();
  }, 200);
});

Return a Promise

In this example, we use the Promise API to return a promise, which is fulfilled when the test completes.

it("should track time", function() {
  return new Promise(function (fulfill, reject){
    var startTime = new Date();

    window.setTimeout(function() {
      var endTime = new Date();
      expect(endTime - startTime).to.equal(200);

      fulfill();
    }, 200);
  });
});

You can also use Chai As Promised for more fluent Promise handling:

it("should track time", function() {
  var promise = new Promise(function (fulfill, reject){
    var startTime = new Date();

    window.setTimeout(function() {
      var endTime = new Date();
      fulfill(endTime - startTime);
    }, 200);
  });

  promise.should.eventually.equal(200)

  return promise;
});

Async Docs

Enjoy Testing? Take it a step further with my free course on Visual Regression Testing with WebdriverIO

Header Photo credit