Consider not using mocha

If you use node.js and you are aware of unit testing, you’ve most likely used mocha at least once. I’ve decided to ditch mocha for lab because the way mocha handles exceptions within tests can lead to confusing results. Consider the following.

describe('The issue is', function() {
  it('this threw an error', function(done) {
    setTimeout(function() { throw 'lol'; }, 10);
    done();
  });

  it('but this should pass', function(done) {
    setTimeout(done, 20);
  });
});

Yields the following output from mocha.

mocha output

Even though the “this threw an error” test threw the error, “but this should pass” is marked as failing. It’s fairly clear what is happening here, but as you introduce more tests, it becomes less clear why “but this should pass” is marked as failing. The reason for this confusion is because mocha listens to the uncaughtException event. In listening to uncaughtException, mocha will fail whichever test is running when it handles the uncaughtException. This is where lab comes in. Lab follows the documentation of uncaughtException to use domains instead. By doing so, lab is able to identify which test created the uncaughtException as can be seen in the following output.

lab output

This identifies the test which caused the exception instead of the test which the exception occurred during. This is much more useful information if you want to figure out what is causing the exception, so consider using lab over mocha.