gpt4 book ai didi

javascript - Sinon Spy 没有捕捉到点击事件

转载 作者:行者123 更新时间:2023-11-28 20:39:19 24 4
gpt4 key购买 nike

我正在使用 Mocha 和 Sinon 来测试点击事件监听器是否已添加到初始化按钮。单击事件在测试中的按钮上触发,但 spy 没有看到它。

我还可以在测试中附加一个点击事件监听器 - spy 会捕捉到它,但该事件会被触发两次。

所以我猜这是一个引用问题 - 访问对 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);
});
});

最佳答案

mock jquery .on() 可能更容易达到相同的结果,它会更单一。

没试过,不过是这样的:

it("", function(){
var spy = sinon.spy();
$ = function(){
return {
on:spy
}
}

sinon.assert.called(spy);
//test the params as well
});

关于javascript - Sinon Spy 没有捕捉到点击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40318046/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com