我有一个导出类的简单模块:
function PusherCom(options) {
}
PusherCom.prototype.lobbyEvent = function(event, message) {
};
module.exports = PusherCom;
我需要./index.js
:
var PusherCom = require('../comms/pusher');
function Play() {
var pusher = new PusherCom();
pusher.lobbyEvent('event', {});
}
我对此应用进行了测试,问题是我如何模拟require('../comms/pusher')
类,或只是lobbyEvent
方法。最好有一个sinon间谍,所以我可以断言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'
如何在nodejs中的某个任意模块中模拟/侦察类中的方法?
答案 0 :(得分:3)
我不是javascript专家,但无论如何我都会抓住机会。而不是监视模块,在lobbyEvent()
实例的pusher
方法中执行此操作,并将其注入Play()
对您的案例来说是一个合理的解决方案吗? 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!