QUnit for javascript Testing on events

2019-08-14 08:15发布

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条回答
太酷不给撩
2楼-- · 2019-08-14 09:14

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);​
查看更多
登录 后发表回答