How to stub out express after you require it with jasmine?

Problem

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;
})();
Problem courtesy of: Toran Billups

Solution

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();
Solution courtesy of: Andreas Köberle

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.