在QUnit测试中无法触发的事件
我是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等无济于事。 此问题在多个浏览器上进行了重复。 我是否正确测试了事件?
完整的repro: http : //jsbin.com/obehu5/edit 。
一旦触发发生,QUnit似乎正在清除元素的事件绑定。 我通过将“init”代码移动到QUnit设置中来解决此问题。 我不确定这是不是一个好的做法,但似乎已经解决了这个问题。 我还修复了上面的示例: http : //jsbin.com/obehu5/5/ 。
将您的ID更改为class级。 每页只允许我唯一的id,所以jquery停止查看第一个id,并且函数永远不会在第二次出现时被触发。
$(document).ready(function(){ //change the id to a class $(".test1").mouseenter(function(){ console.log("enter"); }); $(".test1").mouseleave(function(){ console.log("leave"); }); });
首先尝试创建一个事件对象
例,
var e = jQuery.Event("keydown", true); e.which = 40; // down key e.stopImmediatePropagation();
然后在你的测试中
$('#testEmpty').trigger( e ); // down
没有stopImmediatePropagation我的测试也因多次调用而失败。 这可能会有所帮助。