1

我是 QUnit 的新手。我正在使用 jQuery(用 1.4.2 和 1.5.1 测试)和最新的 QUnit。我可以在单个测试中很好地触发事件,但之后的任何测试都会失败。这是一个简化的重现:

// 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();
});

当我运行测试时,控制台只输出 ENTER。但是,如果我使用单个测试...

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

...控制台输出 ENTER 和 LEAVE。我试过使用 QUnit 的 triggerEvent、jQuery.trigger 等都无济于事。此问题在多个浏览器上重现。我是否正确地测试了事件?

完整重现:http: //jsbin.com/obehu5/edit

4

3 回答 3

2

一旦触发发生,QUnit 似乎正在清除元素的事件绑定。我通过将我的“init”代码移动到 QUnit 设置中解决了这个问题。我不确定这是否是一个好习惯,但它似乎已经解决了这个问题。我还修复了上面的示例:http: //jsbin.com/obehu5/5/

于 2011-03-18T21:45:25.323 回答
0

将您的 id 更改为类。每个页面只允许我唯一的 id,因此 jquery 停止查看第一个 id,并且该函数永远不会在第二次出现时被触发。

$(document).ready(function(){

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

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

});
于 2011-03-18T17:31:45.613 回答
0

先尝试创建一个事件对象

例子,

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

然后在你的测试中

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

如果没有 stopImmediatePropagation,我的测试也由于多次调用而失败。这可能会有所帮助。

于 2011-10-18T14:08:18.840 回答