QUnit for javascript Testing on events

我与影子孤独终老i 提交于 2019-12-24 17:57:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!