Tuesday, 11 June 2019

Within a QUnit test the click event will only fire if the reference is obtained before the test runs

I have the following code that I want to test with Qunit.

// my code under test
document.getElementById('saveButton').addEventListener('click',save);

function save() {
  console.log('save clicked');
}

My QUnit test gets a reference to the button and calls the click function:

(function () {
    "use strict";

    // HACK: with this line here click  works
    //var btn = document.getElementById('saveButton');

    // the test
    QUnit.test("click save", function (assert) {
         // with this line no click
        var btn = document.getElementById('saveButton');
        btn.click(); // will it click?
        assert.ok(btn !== null , 'button found');
    });
}());

Strangely enough if I call getElementById inside Qunit's test method the eventhandler that is attached to the button doesn't get invoked. However, if I move the call to getElementById outside of test function, the event does trigger the click eventhandler.

What is QUnit doing there that prevents that my test from working as expected and what is the proper/recommended way to address the issue I'm facing?

Here is an MCVE (also on JSFiddle) that demonstrates the non-working version. I've commented on what to change to get the click working (working means here: output text to the console)

// code under test
document.getElementById('saveButton').addEventListener('click',save);

function save() {
  console.log('save clicked');
}

// QUnit tests
(function () {
        "use strict";
  // with this line here click  works
  //var btn = document.getElementById('saveButton');
  QUnit.test("click save", function (assert) {
    // with this line no click, comment it to test the working variant
    var btn = document.getElementById('saveButton');
    btn.click(); // will it click?
    assert.ok(btn !== null , 'button found');
  });
}());
<script src="https://code.jquery.com/qunit/qunit-2.9.2.js"></script>
<div id="qunit"></div>
<div id="qunit-fixture">
  <button id="saveButton">test</button>
</div>

It is worth noting that I explicitly don't use jQuery here as the code I'm writing tests for isn't using jQuery either. I'm not yet at the stage I can or am willing to change the code under test.



from Within a QUnit test the click event will only fire if the reference is obtained before the test runs

No comments:

Post a Comment