Setting up a testing infrastructure with Mocha I discovered some impediments which I had to work around. Let’s have a look at the details.
If you want to know more about ES6 Modules, read Axel Rauschmayer's article.
Example Module and Spec
Here is an example module and specification.
[module] [module] --> app/index.js --> test/index.js <-- Mocha [module] ^ Babel
Browserify and Babel
Compiling with Browserify using Babel is pretty easy. You just need to run
browserify -t [ babelify ] app/index.js -o dist/index.js
babelify to be installed:
npm i --save browserify babelify
You can now use the first command as a script in your
I cover the usage of npm as a build tool in another article.
With this we have set up the ES6-to-ES5 compile step which generates a new file which we can use in out application. The next step is to set up testing with Mocha.
Testing with Mocha
You can install Mocha – it's always the same – with npm. You need an assertion library too. I use Chai. You can install both tools like this:
npm i --save mocha chai
Running tests with mocha is as easy as
If you don’t use ES6 and don’t need to transpile to ES5 you’re done with the Mocha setup. Otherwise you will have to do more.
There is an option for Mocha to treat JS as ES6:
--harmony. Unfortunately this
does not implement ES6 Modules and other features. This is why we want to use
--compilers which helps with this:
mocha --compilers js:babel/register test/index.js
Furthermore we need an initial file which is our entry point for Mocha running
on Node.js. I named this file
test/index.js, as you can see.
All it does is it requires Chai and the test suites:
global.chai = require('chai'); global.expect = global.chai.expect; // Load test suites require('../module.spec.js');
You can do more test specific stuff here as for example bootstrapping jsdom.
Test Coverage with Istanbul
It gets a bit tricky if you want to generate coverage reports using
Istanbul. You need to pass the
compiler to the files you want to test and use
_mocha instead of
order to get it to use Babel to compile the JS.
istanbul cover _mocha -- --compilers js:babel/register test/index.js
If you don’t use ES6 and don’t need to transpile to ES5 you can use
istanbul cover mocha test/index.js
Don't forget to install Istanbul:
npm i --save istanbul
To exclude the specification file from the coverage report you can pass the
-x to Istanbul:
istanbul cover _mocha -x '**/*.spec.js' -- --compilers js:babel/register test/index.js
If you searched Google for an hour to fix this workflow and you can finally use all nice features ES6 provides, setting up Mocha with Babel is totally worth it. But luckily I have already done this search.
Have you used Mocha with the latest ES6 features? Which tools did you use? Let me know and tweet me at @drublic.