geeky · non php code

QUnit – test your javascript

After over ten years of javascript programming, I’m finally seriously considering writing at least unit tests for my javascript. Since I’m such a big fan of jQuery, QUnit seems like the obvious choice.

It’s sad but better late than never.

The truth is, in my opinion, the fact that javascript test frameworks do not yet maturely work with many of the continuous integration software deters programmers from using them. What’s the point of unit testing if they don’t automatically get run? Based on my research, JSUnit is the only one that integrates with ANT innately. But JSUnit is more of an abandomware now so people are looking for alternatives.

QUnit + CI topics

>> Run my test suite <<

QUnit simple example:


<!DOCTYPE html>
	<title>Test Suite</title>
	<script src=""></script>
	<link rel="stylesheet" href="" type="text/css" media="screen" />
	<script type="text/javascript" src=""></script>
	<!-- Your source files go here -->
	<script type="text/javascript" src="functions.js"></script>

	<!-- Your tests files go here -->
	<script type="text/javascript" src="isEvenTest.js"></script>
	<script type="text/javascript" src="startsWithTest.js"></script>

	<h1 id="qunit-header">QUnit example</h1>
	<h2 id="qunit-banner"></h2>
	<div id="qunit-testrunner-toolbar"></div>
	<h2 id="qunit-userAgent"></h2>
	<ol id="qunit-tests"></ol>

	<!-- Any HTML you may require for your tests to work properly -->
	<div id="qunit-fixture">test markup, will be hidden</div>

Source javascript file:

function isEven(val) {
	return val % 2 === 0;

function startsWith(data, startsWithStr) {
	data = jQuery.trim(data);
	startsWithStr = jQuery.trim(startsWithStr);
	if(data) {
		return data.toUpperCase().lastIndexOf(startsWithStr.toUpperCase(), 0) === 0;
	} else if(data === startsWithStr) {
		return true;
	} else {
		return false;

Sample test file:



	test('startsWith', function() { 
		ok(startsWith("ll-925", "ll-"), 'Starts with ll-'); 
		ok(!startsWith("ll-925", "xl-"), 'Does not start with xl-'); 
		ok(!startsWith("", "xx-"), 'Does not start with xx-'); 
		ok(startsWith(" xx-sdgj ", "xx-"), 'Trimming test: starts with xx-'); 
		ok(startsWith(" xx-sdgj", " xx- "), 'Trimming test 2: starts with xx-'); 
		ok(startsWith("", " "), 'Empty string starts with empty string'); 
		ok(startsWith("Mn-u59", "mN-"), 'Non case sensitive test'); 
//		raises(startsWith(foo, " "), 'Undefined test 1');  // undefined is obviously not considered a normal exception


>> git repo for the source <<

Additional resources:

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s