我有一个导出类的简单模块:
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方法。最好是一个罪恶的间谍,这样我就可以断言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中任意模块中的类中模拟/监视方法?
发布于 2014-09-17 14:46:21
我不是javascript专家,但我还是会冒险的。与其监视模块,不如在pusher实例的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);
})
})哈哈!
https://stackoverflow.com/questions/25837817
复制相似问题