Javascript Sinon Spy未捕获单击事件
我正在使用Mocha和Sinon测试一个点击事件监听器是否已添加到初始化按钮中。单击事件在测试中的按钮上触发,但间谍没有看到它 我还可以在测试中附加一个click事件监听器——间谍会捕捉到这一点,但事件会触发两次 所以我猜这是一个引用问题——访问main.myMethod的正确引用——并监视它 有人知道我需要做什么才能让它工作吗Javascript Sinon Spy未捕获单击事件,javascript,testing,mocha.js,sinon,jsdom,Javascript,Testing,Mocha.js,Sinon,Jsdom,我正在使用Mocha和Sinon测试一个点击事件监听器是否已添加到初始化按钮中。单击事件在测试中的按钮上触发,但间谍没有看到它 我还可以在测试中附加一个click事件监听器——间谍会捕捉到这一点,但事件会触发两次 所以我猜这是一个引用问题——访问main.myMethod的正确引用——并监视它 有人知道我需要做什么才能让它工作吗 var main = (function() { function init() { $("#btnGo").on('click', myMeth
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);
});
});
var main=(函数(){
函数init(){
美元(“#btnGo”)。点击('click',我的方法);
}
函数myMethod(){
log(“调用了myMethod());
返回true;
}
init();
返回{
init:init,
myMethod:myMethod
}
})();
if(模块类型!==“未定义”&&module.exports!==null){
module.exports=main;
}
/*试验*/
var expect=要求(“柴”)。expect;
var sinon=要求(“sinon”);
var jsdom=require(“jsdom”);
global.document=jsdom.jsdom(“”);
global.window=document.defaultView;
之前(()=>{
$=需要(“jquery”);
全球$=$;
});
描述(“Main.init()”,函数(){
它(“应该将单击事件侦听器附加到按钮。”,function(){
$(“body”).html(“Go”);
var main=require(“../src/main.js”),
spy=sinon.spy(main,“myMethod”);
$('btnGo')。触发(“单击”);
sinon.assert.called(spy);
});
});
在()上模拟jquery可能会更容易。
为了获得相同的结果,它将更加统一
我没试过,但有点像:
it("", function(){
var spy = sinon.spy();
$ = function(){
return {
on:spy
}
}
sinon.assert.called(spy);
//test the params as well
});
感谢您的回复Boris,但听起来像是一个解决办法,当它应该可以简单地监视一个方法。我甚至尝试了一个简单的存根,用main.myMethod=function(){}替换main.myMethod方法;但仍然没有乐趣-我想一定有另一个参考漂浮在某处。。。