Getting started with qunit
by amindunited
HTML
<!-- Load the css for displaying the unit tests -->
<link rel="stylesheet" href="http://code.jquery.com/qunit/qunit-1.12.0.css"/>
<h1 id="heading">jUnit tests</h1>
<span> The tests will check that the heading above exists (ya, pretty obvious, but you know...)</span>
<hr/>
<!-- Button to test interaction -->
<span> The tests will now 'click' on this button which will cause a div with the text 'You clicked?' to be written to the page, and it will check that the element was added successfully</span>
<button id="firstButton">First Button</button>
<hr/>
<!-- div to display the test results -->
<div id="qunit"></div>
<!-- div to hold elements created by and strictly for testing -->
<div id="qunit-fixture"></div>
<script src="http://code.jquery.com/qunit/qunit-1.12.0.js"></script>
JavaScript
$('#firstButton').on('click', function(e){
$('<div></div>')
.attr('id', "response")
.css({'background-color':'yellow'})
.html("You clicked?")
.insertAfter( $(e.target) )
.hide()
.show('fade', 1000);
});
//Tests
//Simple ok test that will always pass
test( "hello test", function() {
ok( 1 == "1", "Passed!" );
});
//Test that the heading element is on the page
test( "Heading Exists", function() {
ok( $('#heading'), "Heading is '"+$('#heading').html()+"'" );
});
//Test that clicking the button creates a 'response' element
test("First Button Behavior", function(){
//trigger click
//$('#firstButton').trigger('click');//using trigger the event runs as though it actually happend
$('#firstButton').triggerHandler('click');//prevents default behavior
//Test that the response element is created
ok( $('#response'), "Found the HTMLElement '" + $('#response').html() + "'");
});