Events Failing To Trigger In QUnit Tests

2019-07-27 14:28发布

I'm new to QUnit. I'm using jQuery (tested with 1.4.2 and 1.5.1) and the latest QUnit. I can trigger events just fine in a single test, but any test afterwards fails. Here's a simplified repro:

// code under test - "#Test1" is just an empty div
$(document).ready(function() {
  $('#Test1').mouseenter(function(e) { console.log('ENTER');});
  $('#Test1').mouseleave(function(e) { console.log('LEAVE');});
});

// tests
test('enter', function() {
    $('#Test1').mouseenter();
});

test('leave', function() {
    $('#Test1').mouseleave();
});

When I run the tests, the console outputs only ENTER. However, if I use a single test...

test('enterleave', function() {
    $('#Test1').mouseenter();
    $('#Test1').mouseleave();
});

...the console outputs ENTER and LEAVE. I've tried using QUnit's triggerEvent, jQuery.trigger, etc. to no avail. This issue repros on multiple browsers. Am I testing events correctly?

Full repro here: http://jsbin.com/obehu5/edit.

3条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-07-27 14:49

Try creating an event object first

Example,

var e = jQuery.Event("keydown", true);
e.which = 40;  // down key
e.stopImmediatePropagation();

Then in your test

$('#testEmpty').trigger( e ); // down  

Without stopImmediatePropagation my test was also failing due to multiple calls. This may help a bit.

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-07-27 14:59

QUnit appears to be clearing the event binding for the element once a trigger occurs. I fixed this issue by moving my "init" code into the QUnit setup. I'm not sure if this is a good practice or not but it seems to have resolved the issue. I also fixed the sample from above: http://jsbin.com/obehu5/5/.

查看更多
等我变得足够好
4楼-- · 2019-07-27 15:15

change your id to a class. only i unique id is allowed per page so jquery stops looking after the first id and the function never gets fired on the second occurance.

$(document).ready(function(){

    //change the id to a class
    $(".test1").mouseenter(function(){
        console.log("enter");
    });

    $(".test1").mouseleave(function(){
        console.log("leave");
    });

});
查看更多
登录 后发表回答