Monday March 10, 2014 - tags:    node.js, testing, sinon

unit testing node.js, stubbing dependencies using sinon

This post will demonstrate how to unit test node.js modules by mocking/stubing dependencies using sinon.

Unit testing node.js is actually very simple once you know how.

Code can be found here: sinon-examples

setup

Create a folder and install the following npm modules to dev dependencies

npm install sinon --save-dev  
npm install should --save-dev  
npm install -g mocha --save-dev  

application

Test stubs are functions (spies) with pre-programmed behavior. Consider the following simple logging module; it has a single function status:

var logger = require("./lib/logger");

module.exports.status = function (){  
  return logger.log();
};

dependencies

It also makes use of a single dependency, ./lib/logger which has a single function log.

var Logger = function(){}

module.exports = new Logger();

Logger.prototype.log = function(message) {  
  return "Info: logging a message";
};

stubbing dependencies

Lets test this module and stub the Logger dependency. Here is a test written using mocha:

  1. We create a new message expected
  2. We require a new logger
  3. We then use sinon to stub the log function to return our new message expected
  4. our test simply calls app.status and asserts that the response of app.status equals expected.
  5. important; we call stub.restore to restore the stubbed module to its original state.
describe('when we stub a single dependency', function () {  
    var expected = "warn: this is a warning";
    var logger = new require('./apps/lib/logger');
    var stub = sinon.stub(logger, "log").returns(expected);
    var app = require('./apps/app');

    it('should respond with a stubbed response', function(done){
      assert.equal(app.status(), expected);
      stub.restore();
      done();
    });
  });