Unit testing request
Well, that was interesting... Had a bit of a challenge this morning as I was starting writing unit tests using nodeunit. One module (interacting with the Facebook graph api) depended quite heavily, not surprisingly, on request. Not wanting to bother Facebook with my unit test (and being able to test the various odd-ball Facebook requests at will) I wanted to be able to mock request, which led me down a 2 hour rabbit hole...
My first intent involved simply overwriting the request module:
var request = require('request'), _request , facebook = require('./facebook.js'); ... _request = request; request = function(...) {...} <do my tests> request = _request;
Not surprisingly, that failed miserably -- my Facebook module doesn't know about this updated dependency! Luckily, Felix Geisendörfer came to the rescue with the handy little sandboxed-module, which "lets you inject dependencies into your modules" - exactly what I needed!
Now, I can write the following:
var requestHandler , facebook = SandboxedModule .require('../facebook.js', { requires: {'request': function(){ requestHandler.apply(this, arguments); }} });
... and later on, during my test, redefine the requestHandler like such:
requestHandler = function(cfg, callback){ callback(false,{},'{}'); } This means I now have complete flexibility over what I'm testing against - thanks Felix!











