JavaScript testing with Mocha, Chai and Grunt

Everyone agrees that TDD (test-driven development) is a good thing and yet very few people do it. why? I believe that one of the reason is pure laziness.  It is too much work to click “Run Test” every single time, however there is another more important reason and that is the “feedback loop”, which in this case is extremely slow.  Just like the IDE monitors every single text you type (unless you’re using VIM – sweet bro!) you need a testing framework that does the same and lets you know immediately when something is failing.  Lets see how to do that in JavaScript.

First, make sure you’ve Node installed, type this in terminal: node -v lets also check your npm (node package manager) is working properly: npm -v

Now create a directory for your project and cd into it.  We need two files ‘Gruntfile.js’ and ‘package.json’ to setup Grunt and let it monitor our files and execute tasks on our behalf.  Lets generate package.json npm init

Install the grunt command line globally

npm install grunt-cli -g

Now set up grunt for your project (–save-dev: updates package.json file)

npm install grunt --save-dev
npm install grunt-contrib-watch --save-dev

And finally – Mocha

npm install mocha --save-dev
npm install grunt-mocha-test --save-dev
npm install chai --save-dev

Now lets configure Gruntfile.js and wire everything up:

module.exports = function(grunt){
		pkg: grunt.file.readJSON('package.json'),
		mochaTest: {
			files: ['test/*.js'],
			options: {
				reporter: 'spec'
		watch: {
			files: ['src/*.js', 'test/*.js'],
			tasks: ['mochaTest']

	grunt.registerTask('default', 'mochaTest');

So this Gruntfile says – please ‘watch’ these sets of files and when anything changes execute the mochaTest task.  And finally let’s fire it up:

grunt watch


Now lets add app-test.js with the following code into test/ directory to see if it’s actually working

var expect = require('chai').expect;

describe('Yes we are grunting', function(){
	it('and ofcourse one should equal one', function(){


Hope this helps Smile