Mocha Tests and ECMAScript 2015

Recently, I tried my hand at testing a library with Mocha and Chai. It went rather well, and I’ve just about integrated testing into my day to day life. I won’t say I’m perfect and the people I work with will attest that they need to remind me sometimes to write tests. Today my problem is testing ECMAScript 2015 script.

I have a nice API for parsing a URI. It’s based on work by Steven Levithan from way back in 2007.  I wanted to bring it up to date and re-write it as a class in ECMAScript 2015.  I won’t bore you with the code – it’s relatively easy.  I obviously want to write tests for this.  Here is the test code:

///<reference path="../typings/mocha/mocha.d.ts"/>
///<reference path="../typings/chai/chai.d.ts"/>
import {expect} from 'chai';
import URL from '../src/url';

describe('URL', function () {
    describe('.constructor()', function () {
        it('should accept a simple URL', function () {
            var e = new URL('');

        it('should accept a loose URL', function () {
            var e = new URL('');

        it('should accept a strict URL', function () {
            var e = new URL('', true);

Note the import mechanisms above the tests. That tells me it’s ES2015 code and not regular javascript. So what happens when you try to run mocha?

Screen Shot 2015-11-25 at 3.21.57 PM

The problem is really that Node.js doesn’t support all the ES2015 syntax yet. I need to transpile. I can do this one of two ways. The obvious one is to transpile the code into a separate directory and then run the mocha tests on that. This is really unsatisfactory. Firstly, I’m going to have to create a gulp job for this to transpile and then run the unit tests because otherwise I’ll forget. Secondly, it’s really increasing the footprint. I can’t just quickly run mocha with an argument to run one test – I have to run a full compile.

That leads me to the second way. I can actually run Mocha with a transpiler. I have to firstly install a mocha transpiler plugin. That’s another npm package:

npm install --save-dev mocha-babel

Make sure you use the same transpiler as you would with your code. If you use traceur normally, then install mocha-traceur instead. Now I can run the tests with a command line argument:

mocha --compilers js:mocha-babel

This will run all the tests on my ES2015 code, transpiling on the fly for me. I can now place this in my package.json as follows:

  "scripts": {
    "test": "mocha --compilers js:mocha-babel"

What about babel options? Well, you can create a file in the root of your project called mocha-babel.js which contains the options you want. For instance:

  'presets': [ 'es2015' ],
  'plugins': [ 'class-properties' ]

The options are passed through to the Babel transpiler as-is, so make sure your options match the version you are using. There was a significant change in options between v5.x and v6.x of Babel.

Now, back to my developing!