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){
	grunt.initConfig({
		pkg: grunt.file.readJSON('package.json'),
		mochaTest: {
			files: ['test/*.js'],
			options: {
				reporter: 'spec'
			}
		},
		watch: {
			files: ['src/*.js', 'test/*.js'],
			tasks: ['mochaTest']
		}
	});

	grunt.loadNpmTasks('grunt-mocha-test');
	grunt.loadNpmTasks('grunt-contrib-watch');
	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

watching

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(){
		expect(1).to.equal(1);
	});
});

running

Hope this helps Smile

Mavenize SqlJdbc Jar

Download SQL Server jdbc driver from here.

Open command prompt and cd into the directory until you see the sqljdbc4.jar file. Run the following command, which will mavenize and install the package in your local .m2 repository.

mvn install:install-file -Dfile=sqljdbc4.jar -DgroupId=com.microsoft.sqlserver -DartifactId=sqljdbc4 -Dversion=4.0 -Dpackaging=jar

Now add the dependency in your pom file

<dependency>

<groupId>com.microsoft.sqlserver</groupId>

<artifactId>sqljdbc4</artifactId>

<version>4.0</version>

</dependency>