我使用Mocha和Sinon来测试在初始化时是否向按钮添加了单击事件侦听器。click事件在测试中触发了按钮,但是间谍没有看到它。
我还可以在测试中附加一个click事件侦听器-间谍将捕获此事件,但事件被触发两次。
所以我猜这是一个引用问题-访问对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
});