Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QUnit not running external JavaScript file

I'm trying to adapt the tutorial here to use QUnit v2.x, but it doesn't seem to be picking up the JavaScript file I want to test.

test.html

<div id="qunit"></div>
<div id="qunit-fixture">
  <form>
    <input name="text" />
    <div class="has-error">Error text</div>
  </form>
</div>

<script src="http://code.jquery.com/jquery.min.js"></script>
<script src="qunit.js"></script>
<script src="../list.js"></script>
<script>

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

</script>

list.js

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

The test fails with a result of true

The provided code in the tutorial works fine with QUnit 1.23

<script>

/*global $, test, equal */

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", function () {
    equal($('.has-error').is(':visible'), true);
});

</script>

Edit: Using QUnit v1.23 both versions of the tests work!

like image 637
James Burke Avatar asked Jul 02 '26 18:07

James Burke


1 Answers

So, this question has come up in multiple other places on SO. Essentially what happened is that QUnit 2 handles fixtures differently. Your code adds an event handler to the original HTML, but then QUnit kills that HTML and rebuilds it, thus removing your handler. The solution is to do the event binding inside your test, not on page load. Here is a fiddle to play with, but the code is below:

  function init() {
    $('.username').on('keypress', function() {
      console.log('hiding error!');
      $('.has-error').hide();
    });
  }

  QUnit.test("errors should be hidden on keypress", function(assert) {
    init();
    $('.username').trigger('keypress');
    assert.strictEqual($('.has-error').is(':visible'), false);
  });

  QUnit.test("errors not be hidden unless there is a keypress", function(assert) {
    init();
    assert.strictEqual($('.has-error').is(':visible'), true);
  });
like image 170
Jordan Kasper Avatar answered Jul 04 '26 09:07

Jordan Kasper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!