TommyBlue.it

Basic setup for a Node.js-based TDD Code Kata

In the last post I suggested a minimal setup to begin with ruby-based TDD. In this post I want to show a possibile minimal setup for node.js-based TDD (node.js and npm must be installed). The kata will be again The Game of Life.

I’m not an expert of Node.js, so I hope what I’m writing is correct :)

I’ll use the test framework Mocha and expect.js, a “Minimalistic BDD-style assertions for Node.JS and the browser”.

Let’s begin with the package.json file which will tell to npm what to install:

{
  "name": "game-of-life",
  "version": "0.0.1",
  "dependencies": {
    "mocha": "*",
    "expect.js": "*"
  }
}

With this file in the project folder you can run npm install to install the libraries. Then create the test/ folder with the mocha.opts file, where you can specify various options, like the reporter to use:

--reporter spec

With this file in place, the mocha command will launch the test. So write the minimal js file and its corresponding test file:

test/game_of_life_test.js:

var expect = require('expect.js'),
  GameOfLife = require('../lib/game_of_life');

describe('Universe', function(){
  it('should have an initial size', function() {
    var u = new GameOfLife(6)
    expect(u.getSize()).to.equal(36);
  });
})

lib/game_of_life.js:

function GameOfLife(side){
  this.size = side * side;
}
GameOfLife.prototype.getSize = function() { return this.size; }

module.exports = GameOfLife;

Now launch mocha and the first test should pass:

~$ mocha

  Universe
    ✓ should have an initial size 

  1 passing

To know something more about TDD and Node.js, start reading this post from Azat Mardan