开发者

Events Failing To Trigger In QUnit Tests

开发者 https://www.devze.com 2023-02-17 13:27 出处:网络
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 ju开发者_运维问答st fine in a single test, but any test afterwards fails. Here\'s a simpli

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 ju开发者_运维问答st 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.


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/.


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");
    });

});


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消