我有一个导出类的简单模块:
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'
如何在Node.js中任意模块内的类中模拟/监视方法?
我不是JavaScript专家,但无论如何我都会把握机会。对于您的情况而言,不是侦听模块,而是lobbyEvent()
使用pusher
实例的方法来执行该模块并将其注入该模块Play()
中是合理的解决方案?例如
// 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!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句