Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Loading…

How to spy on a module ? #250

Open
jackdbernier opened this Issue · 5 comments

3 participants

@jackdbernier

Hi,
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 ?

Thanks

@tebriel

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) {
    request.on(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() {
    funcThing.someFunction('a');
    expect(mockrequest.on).toHaveBeenCalledWith('a');
  });
});

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.

@jackdbernier

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.

@tebriel

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.

@jackdbernier

I came across something like this(https://gist.github.com/jbpros/1135181). I wondered if it would be a nice feature to have.

@Lastalas

You can also look at the Rewire library https://github.com/jhnns/rewire. 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
Something went wrong with that request. Please try again.