Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to spy on a module ? #250

Open
ghost opened this issue Aug 11, 2013 · 5 comments
Open

How to spy on a module ? #250

ghost opened this issue Aug 11, 2013 · 5 comments

Comments

@ghost
Copy link

ghost commented Aug 11, 2013

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
Copy link
Contributor

tebriel commented Aug 11, 2013

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.

@ghost
Copy link
Author

ghost commented Aug 11, 2013

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
Copy link
Contributor

tebriel commented Aug 11, 2013

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.

@ghost
Copy link
Author

ghost commented Aug 11, 2013

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

@davidposin
Copy link
Contributor

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
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants