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>

Java–Pretty print xml string

To print a formatted xml string in Java, first convert the raw string into a Document object, then use Transformer class to format the output like so:

pretty

Now simply call this method to print the formatted xml string for e.g.,

main

output

Spring Mvc–Layout/Master pages

To set up layout pages in Spring you could use SiteMesh. The way you set it up is as follows:

Add the latest version of sitemesh to your pom file, during this writing it was v2.4.2

sitemesh

Create a new decorators.xml file within the WEB-INF folder, this file is used to describe where your layout page is, when it should be used. Here I am telling it that my layout.jsp page is in a folder called shared and that it should be used for any url patterns.

decorators

Now add the following two lines in your web.xml file

webxml

And finally extract all of the common UI elements into the layout.jsp file. Notice the keyword “decorator”, basically the requested page will be decorated by this layout page.

layout

And here is the hello.jsp page.  The layout’s title element will be replaced by “This is hello’s title” and everything else will be put within the body

hello

Spring MVC – CSS and JavaScript imports

In this series we will go through setting up a basic web structure that deals with importing resources (css/javascript), we’ll slowly progress this app in subsequent blog posts by adding layout/master page support as well as reading values from config files.  I will primarily use xml configuration for these setups, you can also do it strictly through code if you’d like, which I might write another blog post later on.

So, coming from a .NET (MVC)/Ruby-On-Rails world where right after start new project, everything is setup for you and ready to go, with Spring MVC, this was definitely not the case.  I struggled with the most basic things, such as how do I import css files? how do I use a common layout page so that I don’t have to repeat myself? how do I use config files? And after searching through the internet, it seems like most new comers to spring mvc are having these same issues as well, which is unfortunate because it is a powerful mvc framework but it seems like they gained that power by making it fat, ugly, and xml hungry Smile. Enough of that lets get started.

Importing css files:

Webjars (http://www.webjars.org/) allows to you to download and use common CSS and JavaScript files using any of the popular packaging tools. For our app we’ll use Maven, here is the pom.xml file to download bootstrap.css files.

pom1

I tried setting up the resource location using xml but that didn’t work, so here is how I did it through code. Add a POJO file to you project, lets call it WebConfig.java with the folloing contents.

webconfigPNG

With this you are ready to start importing css files that are listed in the pom.xml, which in our case is just the bootstrap files, here is the syntax for it:

<link rel="stylesheet" href="/webjars/bootstrap/3.1.1/css/bootstrap.min.css">

Lets also add a custom app.css and app.js files and see how we can set that up as well.  Now our project structure looks like this

projectbar

The “resources” folder is what we have used to put our resources, this is a special folder that spring understands how to deal with, but for some reason we still have to set it up in the dispatcher-servlet.xml file urgh…. (Convention over Configuration – spring please learn).  Here is the dispatcher-servlet.xml

mvc-dispatcher-servlet

We’ve added the “mvc” namespace and its associated schemaLocation information (don’t forget), then finally we can add the mapping and location information.  The two asterisk at the end means, add all folders underneath recursively, in our case both the css and js folders.

Now if you cross your fingers and hit run, everything should work and the resulting page should have all the css/javascript files that we’ve listed.

Here is the sample application on my GitHub

Resource Cleanup functional way

For some applications there might be times when expensive resources must be cleaned up properly or there might be times where your clients are being irresponsible and forget to wrap your class in using statements resulting in memory leaks or open database connections.  These might be a good time to implement the following strategy by where you take full control/responsibility of cleaning your own resources and not allow anybody else to instantiate a new instance of your class.  Lets say we have the following class and a repository implementation mimicking a database service:

person

repo

The first thing you’ll notice in the repository class is that it has a “private constructor” to disallow any callers to create a new instance of this class.  Then it provides to static “Use” methods for the clients, one is void and the other returns T.  Within the Use methods is where you would take control of cleaning up whatever resources needs to be cleaned up, freeing the clients of your class from that burden.  I also believe that cleaning up after yourself is an internal concern and an implementation detail that other classes shouldn’t know about nor care about!  Now the clients can use your class as follows:

main

If you run the program you’ll see that the Dispose method is called each time as you’d expect and the client does not need to remember to wrap any statements in using/try-finally block.

References: Venkat Subramaniam

URL Through JavaScript

JavaScript by default gives you full access to the browser’s url property through the global window.location object.  Let’s use this following url as an example:

“http://www.demo.com/Sports/Running/Shoes?item=1&size=10&color=green”

To get the full url use:

first_full

To only get the origin use:

second

With these two properties you can extract any values that you want using regular string functions, such as:

If you don’t care about the origin use the following.

thrid

If you would like to remove the query string values as well use this

fourth