Reputation: 3460
I have a simple module that exports a class:
function PusherCom(options) {
}
PusherCom.prototype.lobbyEvent = function(event, message) {
};
module.exports = PusherCom;
I require it from my ./index.js
:
var PusherCom = require('../comms/pusher');
function Play() {
var pusher = new PusherCom();
pusher.lobbyEvent('event', {});
}
I have a test for this app, problem is how can I mock require('../comms/pusher')
class, or just the lobbyEvent
method. Preferably with a sinon spy, so I can assert about arguments of lobbyEvent
.
describe 'playlogic', ->
beforeEach, ->
pushMock = ->
@lobbyEvent = (event, message) ->
console.log event
@
// currently I tried proxyquire to mock the require but it doesn't support spying
proxyquire './index.js, { './comms/pusher': pushMock }
it 'should join lobby', (done) ->
@playLogic = require './index.js'
@playLogic.joinedLobby {}, (err, result) ->
// How can I spy pushMock so I can assert the arguments
// assert pushMock.called lobbyEvent with event, 'event'
How can I mock/spy a method within a class within some arbitrary module in nodejs?
Upvotes: 3
Views: 2029
Reputation: 2313
I'm no javascript expert, but I'll take my chances anyway. Rather than spying the module, doing it in the lobbyEvent()
method of the pusher
instance, and injecting it into Play()
would be a reasonable solution for your case? e.g.
// pusher.js
function PusherCom(options) { }
PusherCom.prototype.lobbyEvent = function(event, message) { };
module.exports = PusherCom;
// play.js
function Play(pusher) {
pusher.lobbyEvent("event", { a: 1 });
}
module.exports = Play;
// play_test.js
var assert = require("assert"),
sinon = require("sinon"),
PusherCom = require("./pusher"),
Play = require("./play");
describe("Play", function(){
it("spy on PusherCom#lobbyEvent", function() {
var pusher = new PusherCom(),
spy = sinon.spy(pusher, "lobbyEvent");
Play(pusher);
assert(spy.withArgs("event", { a: 1 }).called);
})
})
HTH!
Upvotes: 4