Sunday, August 28, 2011

BDD Testing Example with Node.js and Jasmine

In Node.js at least, using jasmine is pretty straightforward.  We can use standard Node.js require(.) semantics to include the modules we're testing.  In the prior examples, we defined a couple of modules, one that defines a random number generator and another that returns the current date.  Here, we're going to write some simple specifications we can use to test the services.

First, in the project, create a spec directory.  I created it right next to the lib directory, which holds my source files.  Once that's in place, you can create your specifications. The first specification, the date specification, tests the date service.  You can include the date service source files with using require(.):

var date = require('../lib/date').date;


describe('date specification', function(){


  it('should return a valid value', function(){
    var generator = new date.Generator();
var value = generator.generate();
expect(value).not.toBeNull();
  });


it('should return the current date', function() {
var generator = new date.Generator();
expect(generator.generate().toString()).toEqual(new Date().toString());
});


});


This, we can run this with jasmine-node by executing the command line 'jasmine-node spec' in the directory containing the spec subdirectory.  We can then create an additional suite of tests for the random service:


var random = require('../lib/random').random;


var SEED = 10;
var LOW_SEED = 2;
var MED_SEED = 50;
var HIGH_SEED = 1000;


var evaluator = function(seed) {
var generator = new random.Generator(seed);
var value = generator.generate();
expect(value).not.toBeNull();
expect(value).toBeGreaterThan(-0.001);
expect(value).toBeLessThan(seed);
};


describe('random specification', function() {

it('should return a value between 0 and the seed', function() {
evaluator(SEED);
});

it('should work with a variety of seed values', function() {
evaluator(LOW_SEED);
evaluator(MED_SEED);
evaluator(HIGH_SEED);
});

});

Now, when we execute jasmine-node, we see this (note, I'm using verbose mode here):

prompt> jasmine-node --verbose spec
Started
....


Spec date specification
Spec random specification
Finished in 0.004 seconds
2 tests, 14 assertions, 0 failures

Now we've successfully integrated our jasmine-node tests into our repository, and we can execute them from the command line.  The next step is to integrate them with a continuous integration system like Jenkins.

No comments:

Post a Comment