问题
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');
});
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
回答1:
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");
You can use .dispatchEvent
instead: http://jsfiddle.net/LYxD4/1/.
var event = document.createEvent("HTMLEvents");
event.initEvent("click", true, true);
$(...).get(0).dispatchEvent(event);
来源:https://stackoverflow.com/questions/9670357/qunit-for-javascript-testing-on-events