Babysteps with Node.js and Mocha

Not being a JavaScript expert I still took a special interest in the Node.js sessions during my time at Visual Studio Live Chicago 2013. Running JavaScript server side seemed very intriguing and the examples given made it clear that that setting up a simple web server was a piece of cake. Node.js utilizes the V8 JavaScript Engine to run the scripts you create. Having previously experimented with the HTML5 canvas controll & JavaScript it seems obvious that this engine is far superior to those of the competition.

The best session on this topic at VSLive Chicago was by far the one titled JavaScript, Meet Cloud: Node.js on Windows Azure by Sasha Goldshtein. An excellent speaker covering such topics as deploying Node.js applications to Windows Azure, writing Node.js MVC(ish) applications with Express as well as using the Jade template engine. Sasha seemed to be prepared for any eventuality and seamlessly switched to a pre-recorded video when the Windows Azure management interface once acted up while he was demonstrating a deployment.

My own experimentation resulted in a trivial server application to compute prime numbers and return them as json data. Unit tests were created with the help of the Mocha unit test framework. The server code itself:

var http = require('http');
var url = require('url');
var primecalc = require('primecalc');

var port = 8000;

var server = http.createServer(function (request, response) {
  var number = url.parse(request.url).path.substring(1);
  response.writeHead(200, { "Content-Type": "application/json" });
  var primes = primecalc.getPrimes(number);
  response.end(JSON.stringify(primes));
}); 

server.listen(port);

module.exports = server;

console.log("Server running at http://localhost:" + port + "/");

Integration tests for the server:

var app = require('../primes');
var http = require('http'); 
var assert = require('assert');
describe("Tests for the primes server application\n", function () {
  describe('/', function () {
    it('should return 200', function (done) {
      http.get('http://localhost:8000', function (res) {
        assert.equal(200, res.statusCode);
        done();
      });
    });
  });
  describe('/31', function () {
    it('should return primes between 0 and 31', function (done) {
      http.get('http://localhost:8000/31', function (res) {
        var data = '';
        res.on('data', function (chunk) {
          data += chunk;
        });
        res.on('end', function () {
          assert.equal('[3,5,7,11,13,17,19,23,29,31]', data);
          done();
        });
      });
    });
  });
});

The prime calculating code itself looks like so (and leaves much to be desired):

function primecalc()
{
	this.isPrime = function(number)
	{
		if (number < 2) return false;
		if (number == 2) return true;
		if (number % 2 == 0) return false;
		for (var i = 2; i < number; i++)
		{
			if (number % i == 0) return false; 
		}
		return true;
	}
	this.getPrimes = function(upto)
	{
		var primes = new Array();
		for (var i = 3; i <= upto; i++)
		{
			if (this.isPrime(i)) primes.push(i);
		}
		return primes;
	}
}
module.exports = new primecalc();

Unit tests for the prime number generator:

var app = require('../lib/primecalc'); 
var assert = require('assert');
describe("Tests for the primecalc class\n", function () {
	describe("\tTesting the getPrimes function\n", function () {
		describe("\t\tWhen it is called with upto = 31\n", function () {
			it("\t\t\tshould return all primes between 0 and 31\n", function () {
				var primes = app.getPrimes(31);
				assert.deepEqual(primes, [3, 5, 7, 11, 13, 17, 19, 23, 29, 31]);
			});
		});
	});
	describe("\tTesting the getPrimes function\n", function () {
		describe("\t\tWhen it is called with upto = 0\n", function () {
			it("\t\t\tshould return an empty array\n", function () {
				var primes = app.getPrimes(0);
				assert.deepEqual(primes, []);
			});
		});
	});
	describe("\tTesting the isPrime function\n", function () {
		describe("\t\tWhen it is called with prime value\n", function () {
			it("\t\t\tshould return true\n", function () {
				var primes = app.isPrime(13);
				assert.equal(primes, true);
			});
		});
	});
	describe("\tTesting the isPrime function\n", function () {
		describe("\t\tWhen it is called with a non prime value\n", function () {
			it("\t\t\tshould return false\n", function () {
				var primes = app.isPrime(64);
				assert.equal(primes, false);
			});
		});
	});
});

The main challenges putting this together had to do with testing the json data returned by the server itself (had to do a fair bit of Googling for that) as well as how to reference external code (primecalc) in a Node.js application. The only way I got Node to resolve it was by creating a minimal package (with an index.js file) under the node_modules directory (under the project directory). Trying to simply link in an external js file was a complete no-go. To run the unit tests I resorted to simple command files but realise that setting up a proper Make file would make it much more convenient (next post perhaps). I guess I have become a bit spoiled by the way the .NET framework and Visual Studio serves everything up for you. Every little snag with Node.js and Mocha was maddening but getting the tests to finally run was very satisfying.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s