Using the jQuery test suite for your own projects
Your test page needs to include these files:
- jquery.js (just the standard jQuery build, can be compressed)
- testrunner.js and testsuite.css (in the jQuery repository within build/test/data/ or within test/ after the testsuite was built)
Every test is called by test(). The first parameter is the name of the test, the second a function that runs the actual test code and any assertions.
The most useful assertion is ok(). It is just the same is assertTrue() in JUnit or similar frameworks.
A simple setup looks like this:
<link rel="Stylesheet" media="screen" href="data/testsuite.css" />
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="testrunner.js"></script>
<script>
test("jQuery()", function() {
ok( Array.prototype.push, "Array.push()" );
ok( Function.prototype.apply, "Function.apply()" );
ok( document.getElementById, "getElementById" );
ok( document.getElementsByTagName, "getElementsByTagName" );
ok( RegExp, "RegExp" );
ok( jQuery, "jQuery" );
ok( $, "$()" );
});
test("length()", function() {
ok( $("div").length == 2, "Get Number of Elements Found" );
});
</script>
The test suite expects an element with the id "main". Before running any tests, it saves the innerHTML of "main" and restores that after every test.
Also add an ordered list with an id "tests" to hold the results of the test run.
If you need to reset within a single test, you can call reset().
When testing asynchronous code, you should call stop() before anything else, and start() after all assertions. If something fails, start() may never be called. To allow further tests to run, there is a timeout of two seconds that calls start().
You can specify the number of expected assertions by calling expect(Number) at the start of your test.
Other assertions available are isSet(), q(), and t(). See the comments in testrunner.js for details.
This is a test from the ajax module using expect(), stop() and start():
test("$.ajax - simple get", function() {
expect(1);
stop();
$.ajax({
type: "GET",
url: "data/name.php?name=foo",
success: function(msg){
ok( msg == 'bar', 'Check for GET' );
start();
}
});
});
