wxcoder wxcoder - 4 months ago 33
jQuery Question

Triggering JavaScript events in Qunit tests

I am trying to test that when a user clicks in my form the existing error message will go away. For some reason the last test is failing and i'm not sure why. I'm fairly new to jQuery and Qunit.

test.html



<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Javascript tests</title>
<link rel="stylesheet" href="qunit.css">
</head>

<body>
<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 type="text/javascript">

test("errors should be hidden on key press", function() {
$('input[name="text"]').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);
});

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

</script>

</body>
</html>


list.js



jQuery(document).ready(function ($) {
$('input[name="text"]').on('keypress', function() {
$('.has-error').hide();
});

$('input[name="text"]').on('click', function() {
$('.has-error').hide();

});
})

Answer
function setupModule() {
    $('input[name="text"]').on('click', function() {
         $('.has-error').hide();
    })
    $('input[name="text"]').on('keypress', function() {
        $('.has-error').hide();
    });
}

module('tests', {setup:setupModule});

test("errors should be hidden on key press", function() {
     $('input[name="text"]').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);
 });


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

http://jsfiddle.net/u3v08v1e/13/