问题描述
我真的是javascript测试的新手.我能够测试qunit的所有其他功能.但是无法弄清楚如何使用qunit测试事件处理程序功能.在看到jquery event.js测试套件中的触发器,绑定&的示例后,我尝试了以下方法委托功能.
Im really new to javascript testing. I'm able to test all other functions of qunit.But couldn't figure out how to use qunit to test event handler functionalities. I tried the below after seeing a sample in jquery event.js test suite for trigger, bind & delegate functions.
test('Event Handling', function () {
var hai = function() {
console.log('Clicked');
ok(true, 'click event triggered');
};
eventLib.addEvent(document.getElementById('qunit-header'), 'click', hai);
$('#qunit-header').trigger('click');
ok(true, 'It happend');
});
在这里eventLib是我编写的用于附加和分离事件的函数.但是上面的代码似乎在qunit html接口上没有提供任何输出[除了它发生].但是,如果我手动单击标题,则事件处理程序将记录到控制台.我正在使用jquery v1.6.2
Here eventLib is a function that I have written to attach and detach events. But the above code doesn't seem to give any kind of output on qunit html interface [except It happend]. But if I manually click the header, event handler logs to console. I'm using jquery v1.6.2
推荐答案
似乎.trigger
仅运行通过jQuery绑定的事件,而不通过其他方式运行.在Chrome上,这只会记录jquery
: http://jsfiddle.net/LYxD4/.
It seems .trigger
only runs events bound through jQuery, not through another way. On Chrome, this only logs jquery
: http://jsfiddle.net/LYxD4/.
$("#x").get(0)
.addEventListener("click", console.log.bind(console, "native"),
false);
$("#x").on("click", console.log.bind(console, "jquery"));
$("#x").trigger("click");
您可以改用.dispatchEvent
: http://jsfiddle.net/LYxD4/1/.
var event = document.createEvent("HTMLEvents");
event.initEvent("click", true, true);
$(...).get(0).dispatchEvent(event);
这篇关于QUnit用于事件的javascript测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!