Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QUnit fails tests inconsistently/alternately

I have a simplified QUnit test which consists of 2 simple tests that fails randomly/alternately for no good reason (They are both atomic, meaning that one test doesn't change anything of the other element)

Please see this jsFiddle try to run multiple times

module("Basic actionBind");
//two simple tests
test("action1", function() {
    ok(ele2.trigger("click").hasClass("clicked"), "basic click action");
});

test("action2", function() {
    ok(ele1.click().hasClass("clicked"), "basic click action");
});
like image 595
adardesign Avatar asked May 08 '13 15:05

adardesign


1 Answers

The problem is in the caching of the jQuery objects in the global context at run-time. Here's two snippets from your code (from the link in your question: http://jsfiddle.net/adardesign/aZRK7/12/):

HTML:

<div id="qunit-fixture">
    <span id="ele1" class="action" data-action="action1"></span>
    <span id="ele2" class="action" data-action="action2" ></span>
</div>

JS:

// caching elements
var $ele1 = $('#ele1'),
    $ele2 = $('#ele2');

test('action1', function() {
    ok($ele2.trigger('click') ....


test('action2', function () {
    ok($ele1.trigger('click') ....

The actual elements are inside the #qunit-fixture which is reset and re-parsed for each test, thus the click events you fired from inside the tests were triggered on the elements that are now no longer in the document. Instead those elements have been detached and #qunit-fixture has been re-parsed from the original html text, thus creating new DOM elements.

I've forked your jsFiddle and revised it accordingly: http://jsfiddle.net/aZRK7/15/

Though I cleaned up various parts before I noticed it, the essential change is moving the query for the element to inside the test:

test('foo', function() {
    var $foo = $('#ele1');
    ok($foo.trigger('click') ....


test('bar', function () {
    var $bar = $('#bar');
    ok($bar.trigger('click') ....
like image 103
Timo Tijhof Avatar answered Nov 04 '22 14:11

Timo Tijhof