Mocha and Istanbul in 5 minutes

February 19, 2018

Who is this for?

This post is for you if:

or

I was in the second situation recently and decided to write everything down while it’s still fresh.

Context

You have a Node.js project, but no tests (yet), and you need just enough to get started.

I put all the files you’ll need on github.

This is not a tutorial on how to write tests or how to use Mocha/Istanbul … but there are some pointers at the end of the post.

Step by step

1. Install your dependencies

$ npm install --save-dev mocha nyc

2. Create the test directory

$ mkdir test
$ # paste the following code in test/example.js

test/example.js

const assert  = require('assert');

const pluralize = require('../lib/example').pluralize;

describe('example', function () {
  describe('pluralize', function () {
    it('keeps singular when count is 1', function () {
      assert.strictEqual(pluralize(1, 'cat'), '1 cat');
    });
  });
});

3. Create a file to test

$ mkdir lib
$ # paste the following code in lib/example.js

lib/example.js

exports.pluralize = function (count, singular, plural) {
  if (count === 1) {
    return `${count} ${singular}`;
  }
  plural = plural || `${singular}s`;
  return `${count} ${plural}`;
};

4. Edit scripts in package.json

Open your package.json and make sure the scripts section looks like:

"scripts": {
  "test":     "mocha --reporter dot",
  "coverage": "nyc --reporter html --reporter text npm test"
}

5. Run your tests

$ npm test

6. Run your test coverage

$ npm run coverage
$ # open coverage/index.html

Overtime

We have tests, we can run them, and we have test coverage: done!

Comments:

Test coverage is poor, on purpose; to show you how useful Istanbul can be:

code coverage for example.js

In this case, you would need more tests:

// covers `else`
it('uses explicit plural when given', function () {
  assert.strictEqual(pluralize(3, 'mouse', 'mice'), '3 mice');
});

// covers line 6, after `||`
it('uses implicit plural otherwise', function () {
  assert.strictEqual(pluralize(3, 'cat'), '3 cats');
});

What’s describe and it? Refer to the excellent mocha documentation.

Mocha, by default, runs tests from test/*.js, that’s why we didn’t need to specify test files or directories.

I kept things simple and used Node.js’s assert library.

When things get complicated, you’ll probably need sinon. Here’s a good tutorial.

Discuss on Twitter