Search code examples
jqueryeventsqunit

Events Failing To Trigger In QUnit Tests


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.


Solution

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