Testing and code coverage using grunt-mocha-istanbul in Sails js

Lately, I have been into node js, particularly to a MVC framework, Sails js. It’s pretty simple to use.

Installing Sails:

sudo npm install -g sails

To create a new Sails app,

sails new My-Awesome-Project

sails-new

cd My-Awesome-Project

cd-My-Project

Launch your sails app:

sails lift

sails-lift

You can find various blogs and tutorials for sails js. Sailscast by Ponzicoder is highly recommended to begin with. In this post, I will be showing how to write tests for sails js apps (version >= 0.10.4).

First you need to install CLI for grunt globally.

sudo npm install -g grunt-cli

Install following dependencies

npm install mocha --save-dev

npm install assert --save-dev

npm install sinon --save-dev

Install grunt-mocha-istanbul

npm install grunt-mocha-istanbul --save-dev

Create a file mocha_istanbul.js in tasks/config with following contents:

module.exports = function(grunt) {
	grunt.config.set('mocha_istanbul', {
		coverage: {
			src: 'test', // the folder, not the files
			options: {
				coverageFolder: 'coverage',
				mask: '**/*.spec.js',
				root: 'api/'
				}
			}
		});
		grunt.loadNpmTasks('grunt-mocha-istanbul');
	};

Create a file test.js in tasks/register with following content

module.exports = function (grunt) {
	grunt.registerTask('test', [
		'mocha_istanbul:coverage'
	]);
};

Create a folder named test in root folder of your project and it should mimic the api folder generated by sails.

dir-structure

Create an api in sails

sails generate api Foo

generate-Foo-api

Add an index action to the FooController

module.exports = {
	index: function(req, res){
		res.send('Hello, world!');
	}
};

Create a test file for FooController with name FooController.spec.js in test/controllers with following content.

var FooController = require('../../api/controllers/FooController');	
var sinon = require('sinon');	
var assert = require('assert');	
describe('The FooController', function() {
	describe('when we invoke the index action', function() {
		it('should return hello world message', function() {
			var send = sinon.spy();
			FooController.index(null,{
				'send': send
			});
			assert(send.called);
			assert(send.calledWith('Hello, world!'));
		});
	});	
});

From terminal, type in the command

grunt test

grunt-test

The whole project is available here and further reference can be found here

Happy coding! :)