Sinon Spy not catchching click event
问题描述:
我正在使用Mocha和Sinon来测试单击事件侦听器已添加到初始化按钮上。点击事件在测试中的按钮上被触发,但是间谍没有看到它。Sinon Spy not catchching click event
我也可以在测试中附加一个点击事件监听器 - 间谍会捕获这个,但事件被触发两次。
所以我猜这是一个参考问题 - 访问main.myMethod的正确引用 - 并监视它。
任何人都知道我需要做些什么才能使它工作?
var main = (function() {
function init() {
$("#btnGo").on('click', myMethod);
}
function myMethod() {
console.log("myMethod() was called");
return true;
}
init();
return {
init: init,
myMethod: myMethod
}
})();
if (typeof module !== "undefined" && module.exports !== null) {
module.exports = main;
}
/*Test*/
var expect = require("chai").expect;
var sinon = require('sinon');
var jsdom = require("jsdom");
global.document = jsdom.jsdom('<body></body>');
global.window = document.defaultView;
before(() => {
$ = require("jquery");
global.$ = $;
});
describe("Main.init()", function() {
it("should attach a click event listener to the button.", function() {
$("body").html("<button id='btnGo'>Go</button>");
var main = require("../src/main.js"),
spy = sinon.spy(main, "myMethod");
$('#btnGo').trigger("click");
sinon.assert.called(spy);
});
});
答
它可能会更容易嘲笑的jQuery .on()
来达到同样的效果,这将是较为一致的。
没有尝试,但这样的:
it("", function(){
var spy = sinon.spy();
$ = function(){
return {
on:spy
}
}
sinon.assert.called(spy);
//test the params as well
});
感谢您的回复,但鲍里斯听起来像当它应该是可以简单地在一个方法窥探一个解决方法。我甚至通过用main.myMethod = function(){}替换main.myMethod方法来尝试一个简单的存根。但仍然没有喜悦 - 我想在另一个地方浮现另一个参考...... – whatever