2

I'm trying to get the code below under test when occurred to me that I already included express at the top of this file. Can you some how monkey patch the express object after it's already loaded?

var express = require('express')

Helper = (function() {                                                                           

  var HelperObject = function(params) {
    this.directories = params.directories;
  };

  HelperObject.prototype.addStaticPath = function(app) {
    for(i = 0; i < this.directories.length; i++) {                                               
      var static = express.static('/public');
      app.use(static);
    }
  };

  return HelperObject;
})();
Toran Billups
  • 27,111
  • 40
  • 155
  • 268
  • for now I've decided to pass in both express and app so I can test the interaction in true isolation. That said, I'd still like to know if anyone has done what I described above. – Toran Billups Sep 10 '12 at 15:54

1 Answers1

2

The problem is that when you create a node module the required modul is bound in the closure of the module and you can't start spying on it cause it isn't visible in your test.

There is Gently where you can override require but it will sprinkle your code with boilerplate test related code.

From the docs:

Returns a new require functions that catches a reference to all required modules into gently.hijacked.

To use this function, include a line like this in your 'my-module.js'.

if (global.GENTLY) require = GENTLY.hijack(require);

var sys = require('sys');
exports.hello = function() {
  sys.log('world');
};

Now you can write a test for the module above:

var gently = global.GENTLY = new (require('gently'))
  , myModule = require('./my-module');

gently.expect(gently.hijacked.sys, 'log', function(str) {
  assert.equal(str, 'world');
});

myModule.hello();
Community
  • 1
  • 1
Andreas Köberle
  • 106,652
  • 57
  • 273
  • 297