Search code examples
javascriptjqueryunit-testingqunit

Qunit click trigger test causes infinite refresh loop


I'm trying to write some qunit tests for a simple jQuery function. The function I'm testing selects an element input, and adds a listener to it (on click and on keypress). The listener hides another element, .has-error:

$('input').on('keypress click', function () {
    $('.has-error').hide();
});

I started with two tests: one that checks that .has-error is invisible after a keypress, and another on that checks that .has-error is visible if nothing happens:

test("errors should be hidden on keypress", function () {
    $('input').trigger('keypress');
    equal($('.has-error').is(':visible'), false);
});

test("errors not be hidden unless there is a keypress or a click",
     function() {
    equal($('.has-error').is(':visible'), true);
});

That works fine, and my tests pass. The problem starts when I try adding a third test, to check that .has-error is hidden after a click on the input element:

test("errors should be hidden on click", function () {
    $('input').trigger('click');
    equal($('.has-error').is(':visible'), false);
});

Then my testing page enters an infinite loop. It seems that both the first and last test are failing. However, removing the first test does not appear to solve the issue.

I guess there's something wrong with my third test, but can't figure out what it is.


Solution

  • Found out what was wrong. It turns out that my selector, $('input'), was too general: there is at least one other element that gets captured by that selector on Qunit's testing page.

    Using the id of the form's input element instead worked.