How to spy on a module ? #250

jackdbernier opened this Issue Aug 11, 2013 · 5 comments


None yet

3 participants


I would like to spy on a node module (in my case request).

Is there a way in jasmine-node to do it ? Otherwise, would it be nice to have something like spyOnModulebuilt-in ?



Best way would be to inject request into your code you want to test and then spy on individual bits in request.
Something like:

var myFunc = function(request) {
  this._request = request;
  this.someFunction = function(someArg) {

then your spec could look like:

describe("Tester", function() {
  var funcThing, mockrequest;
  beforeEach(function() {
    mockrequest = jasmine.createSpyObj('request', ['on', 'off']);
    funcThing = new myFunc(mockrequest);
  it("Calls on", function() {

Hopefully that gives you a good idea of what's going on. I mostly write coffeescript, so forgive me if there are typos, also I didn't test it. Let me know if that clears things up for you.


Thanks @tebriel, I ended up doing something similar to make it works, but I still think it's a bit of a workaround.

Now instead of simply doing

var MyModule = require('MyModule');

I will need to do

var request = require('request');
var MyModule = require('MyModuel')(request);

Which I don't really like.


Hmm. I also seem to recall that within an app, things only get imported once with require and then everyone gets the same instance. It might be worth requiring request within your test and spying on it from in there and see if there are two separate instances or not.


I came across something like this( I wondered if it would be a nice feature to have.


You can also look at the Rewire library It will let you overwrite module properties and methods with your own. You can use it to pass your testing callbacks to check your spies or expects.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment