Reputation: 2387
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!
Upvotes: 3
Views: 1117
Reputation: 13273
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);
});
Upvotes: 3