Advertisement
  1. Code
  2. JavaScript

How to Test your JavaScript Code with QUnit

Scroll to top

QUnit, developed by the jQuery team, is a great framework for unit testing your JavaScript. In this tutorial, I'll introduce what QUnit specifically is, and why you should care about rigorously testing your code.

What is QUnit

QUnit is a powerful JavaScript unit testing framework that helps you to debug code. It's written by members of the jQuery team, and is the official test suite for jQuery. But QUnit is general enough to test any regular JavaScript code, and it's even able to test server-side JavaScript via some JavaScript engine like Rhino or V8.

If you're unfamiliar with the idea of "unit testing", don't worry. It's not too difficult to understand:

In computer programming, unit testing is a software verification and validation method in which a programmer tests if individual units of source code are fit for use. A unit is the smallest testable part of an application. In procedural programming a unit may be an individual function or procedure.

This is quoted from Wikipedia. Simply put, you write tests for each functionality of your code, and if all of these tests are passed, you can be sure that the code will be bug-free (mostly, depends on how thorough your tests are).

Why You Should Test Your Code

If you haven't written any unit tests before, you probably just apply your code to a website directly, click for a while to see if any problem occurs, and try to fix it as you spot one. There are many problems with this method.

First, it's very tedious. Clicking actually is not an easy job, because you have to make sure everything is clicked and it's very likely you'll miss one thing or two. Second, everything you did for testing is not reusable, which means it's not easy to find regressions. What is a regression? Imagine that you wrote some code and tested it, fixed all the bugs you found, and published it. Then, a user sends some feedback about new bugs, and requests some new features. You go back to the code, fix these new bugs and add these new features. What might happen next is that some of the old bugs come up again, which are called "regressions." See, now you have to do the clicking again, and chances are you won't find these old bugs again; even if you do, it'll take a while before you figure out that the problem is caused by regressions. With unit testing, you write tests to find bugs, and once the code is modified, you filter it through the tests again. If a regression appears, some tests will definitely be failed, and you can easily spot them, knowing which part of the code contains the bug. Since you know what you have just modified, it can easily be fixed.

Another advantage of unit testing is especially for web development: it eases the testing of cross-browser compatibility. Just run your tests on different browsers, and if a problem occurs on one browser, you fix it and run these tests again, making sure it doesn't introduce regression on other browsers. You can be sure that all of the target browsers are supported, once they all pass the tests.

I'd like to mention one of John Resig's projects: TestSwarm. It takes JavaScript unit testing to a new level, by making it distributed. It's a website that contains many tests, anyone can go there, run some of the tests, then return the result back to server. In this way, code can be tested on different browsers and even different platforms really quickly.

How to Write Unit Tests with QUnit

So how do you write unit tests with QUnit exactly? First, you need to set up a testing environment:

1
2
<!DOCTYPE html>
3
<html>
4
<head>
5
	<title>QUnit Test Suite</title>
6
	<link rel="stylesheet" href="http://github.com/jquery/qunit/raw/master/qunit/qunit.css" type="text/css" media="screen">
7
	<script type="text/javascript" src="http://github.com/jquery/qunit/raw/master/qunit/qunit.js"></script>
8
	<!-- Your project file goes here -->
9
	<script type="text/javascript" src="myProject.js"></script>
10
	<!-- Your tests file goes here -->
11
	<script type="text/javascript" src="myTests.js"></script>
12
</head>
13
<body>
14
	<h1 id="qunit-header">QUnit Test Suite</h1>
15
	<h2 id="qunit-banner"></h2>
16
	<div id="qunit-testrunner-toolbar"></div>
17
	<h2 id="qunit-userAgent"></h2>
18
	<ol id="qunit-tests"></ol>
19
</body>
20
</html>

As you can see, a hosted version of QUnit framework is used here.

The code that is going to be tested should be put into myProject.js, and your tests should be inserted into myTests.js. To run these tests, simply open this HTML file in a browser. Now it's time to write some tests.

The building blocks of unit tests are assertions.

An assertion is a statement that predicts the returning result of your code. If the prediction is false, the assertion has failed, and you know that something has gone wrong.

To run assertions, you should put them into a test case:

1
2
// Let's test this function

3
function isEven(val) {
4
	return val % 2 === 0;
5
}
6
7
test('isEven()', function() {
8
	ok(isEven(0), 'Zero is an even number');
9
	ok(isEven(2), 'So is two');
10
	ok(isEven(-4), 'So is negative four');
11
	ok(!isEven(1), 'One is not an even number');
12
	ok(!isEven(-7), 'Neither is negative seven');
13
})

Here we defined a function, isEven, which detects whether a number is even, and we want to test this function to make sure it doesn't return wrong answers.

We first call test(), which constructs a test case; the first parameter is a string that will be displayed in the result, and the second parameter is a callback function that contains our assertions. This callback function will get called once QUnit is run.

We wrote five assertions, all of which are boolean. A boolean assertion expects its first parameter to be true. The second parameter is also a message that will be displayed in the result.

Here is what you get, once you run the test:

a test for isEven()a test for isEven()a test for isEven()

Since all these assertions have successfully passed, we can be pretty sure that isEven() will work as expected.

Let's see what happens if an assertion has failed.

1
2
// Let's test this function

3
function isEven(val) {
4
	return val % 2 === 0;
5
}
6
7
test('isEven()', function() {
8
	ok(isEven(0), 'Zero is an even number');
9
	ok(isEven(2), 'So is two');
10
	ok(isEven(-4), 'So is negative four');
11
	ok(!isEven(1), 'One is not an even number');
12
	ok(!isEven(-7), 'Neither does negative seven');
13
14
	// Fails

15
	ok(isEven(3), 'Three is an even number');
16
})

Here is the result:

a test contains failed assertion for isEven()a test contains failed assertion for isEven()a test contains failed assertion for isEven()

The assertion has failed because we deliberately wrote it wrong, but in your own project, if the test doesn't pass, and all assertion are correct, you know a bug has been found.

More Assertions

ok() is not the only assertion that QUnit provides. There are other kinds of assertions that are useful when testing your project:

Comparison Assertion

The comparison assertion, equals(), expects its first parameter (which is the actual value) is equal to its second parameter (which is the expected value). It's similar to ok(), but outputs both actual and expected values, making debugging much easier. Like ok(), it takes an optional third parameter as a message to be displayed.

So instead of:

1
2
test('assertions', function() {
3
	ok( 1 == 1, 'one equals one');
4
})
a boolean assertiona boolean assertiona boolean assertion

You should write:

1
2
test('assertions', function() {
3
	equals( 1, 1, 'one equals one');
4
})
a comparison assertiona comparison assertiona comparison assertion

Notice the last "1", which is the comparing value.

And if the values are not equal:

1
2
test('assertions', function() {
3
	equals( 2, 1, 'one equals one');
4
})
a failed comparison assertiona failed comparison assertiona failed comparison assertion

It gives a lot more information, making life a lot easier.

The comparison assertion uses "==" to compare its parameters, so it doesn't handle array or object comparison:

1
2
test('test', function() {
3
	equals( {}, {}, 'fails, these are different objects');
4
	equals( {a: 1}, {a: 1} , 'fails');
5
	equals( [], [], 'fails, there are different arrays');
6
	equals( [1], [1], 'fails');
7
})

In order to test this kind of equality, QUnit provides another kind assertion: identical assertion.

Identical Assertion

Identical assertion, same(), expects the same parameters as equals(), but it's a deep recursive comparison assertion that works not only on primitive types, but also arrays and objects. Assertions, in the previous example, will all pass if you change them to identical assertions:

1
2
test('test', function() {
3
	same( {}, {}, 'passes, objects have the same content');
4
	same( {a: 1}, {a: 1} , 'passes');
5
	same( [], [], 'passes, arrays have the same content');
6
	same( [1], [1], 'passes');
7
})

Notice that same() uses '===' to do comparison when possible, so it'll come in handy when comparing special values:

1
2
test('test', function() {
3
	equals( 0, false, 'true');
4
	same( 0, false, 'false');
5
	equals( null, undefined, 'true');
6
	same( null, undefined, 'false');
7
})

Structure Your Assertions

Putting all assertions in a single test case is a really bad idea, because it's very hard to maintain, and doesn't return a clean result. What you should do is to structure them, put them into different test cases, each aiming for a single functionality.

You can even organize test cases into different modules by calling the module function:

1
2
module('Module A');
3
test('a test', function() {});
4
test('an another test', function() {});
5
6
module('Module B');
7
test('a test', function() {});
8
test('an another test', function() {});
structure assertionsstructure assertionsstructure assertions

Asynchronous Test

In previous examples, all assertions are called synchronously, which means they run one after another. In the real world, there are also many asynchronous functions, such as ajax calls or functions called by setTimeout() and setInterval(). How can we test these kinds of functions? QUnit provides a special kind of test case called "asynchronous test," which is dedicated to asynchronous testing:

Let's first try to write it in a regular way:

1
2
test('asynchronous test', function() {
3
	setTimeout(function() {
4
		ok(true);
5
	}, 100)
6
})
an incorrent example of asychronous testan incorrent example of asychronous testan incorrent example of asychronous test

See? It's as if we didn't write any assertion. This is because the assertion ran asynchronously, by the time it got called, the test case had already finished.

Here is the correct version:

1
2
test('asynchronous test', function() {
3
	// Pause the test first

4
	stop();
5
	
6
	setTimeout(function() {
7
		ok(true);
8
9
		// After the assertion has been called,

10
		// continue the test

11
		start();
12
	}, 100)
13
})
a correct example of asychronous testa correct example of asychronous testa correct example of asychronous test

Here, we use stop() to pause the test case, and after the assertion has been called, we use start() to continue.

Calling stop() immediately after calling test() is quite common; so QUnit provides a shortcut: asyncTest(). You can rewrite the previous example like this:

1
2
asyncTest('asynchronous test', function() {
3
	// The test is automatically paused

4
	
5
	setTimeout(function() {
6
		ok(true);
7
8
		// After the assertion has been called,

9
		// continue the test

10
		start();
11
	}, 100)
12
})

There is one thing to watch out for: setTimeout() will always call its callback function, but what if it's a custom function (e.g, an ajax call). How can you be sure the callback function will be called? And if the callback is not called, start() won't be called, and the whole unit testing will hang:

unit testing hangsunit testing hangsunit testing hangs

So here is what you do:

1
2
// A custom function

3
function ajax(successCallback) {
4
	$.ajax({
5
		url: 'server.php',
6
		success: successCallback
7
	});
8
}
9
10
test('asynchronous test', function() {
11
	// Pause the test, and fail it if start() isn't called after one second

12
	stop(1000);
13
	
14
	ajax(function() {
15
		// ...asynchronous assertions

16
17
		start();
18
	})
19
})

You pass a timeout to stop(), which tells QUnit, "if start() isn't called after that timeout, you should fail this test." You can be sure that the whole testing won't hang and you'll be notified if something goes wrong.

How about multiple asynchronous functions? Where do you put the start()? You put it in setTimeout():

1
2
// A custom function

3
function ajax(successCallback) {
4
	$.ajax({
5
		url: 'server.php',
6
		success: successCallback
7
	});
8
}
9
10
test('asynchronous test', function() {
11
	// Pause the test

12
	stop();
13
	
14
	ajax(function() {
15
		// ...asynchronous assertions

16
	})
17
18
	ajax(function() {
19
		// ...asynchronous assertions

20
	})
21
22
	setTimeout(function() {
23
		start();
24
	}, 2000);
25
})

The timeout should be reasonably long enough to allow both callbacks to be called before the test continues. But what if one of the callback isn't called? How can you know that? This is where expect() comes in:

1
2
// A custom function

3
function ajax(successCallback) {
4
	$.ajax({
5
		url: 'server.php',
6
		success: successCallback
7
	});
8
}
9
10
test('asynchronous test', function() {
11
	// Pause the test

12
	stop();
13
14
	// Tell QUnit that you expect three assertions to run

15
	expect(3);
16
17
	ajax(function() {
18
		ok(true);
19
	})
20
21
	ajax(function() {
22
		ok(true);
23
		ok(true);
24
	})
25
26
	setTimeout(function() {
27
		start();
28
	}, 2000);
29
})

You pass in a number to expect() to tell QUnit that you expect X many assertions to run, if one of the assertion isn't called, the number won't match, and you'll be notified that something went wrong.

There is also a shortcut for expect(): you just pass the number as the second parameter to test() or asyncTest():

1
2
// A custom function

3
function ajax(successCallback) {
4
	$.ajax({
5
		url: 'server.php',
6
		success: successCallback
7
	});
8
}
9
10
// Tell QUnit that you expect three assertion to run

11
test('asynchronous test', 3, function() {
12
	// Pause the test

13
	stop();
14
15
	ajax(function() {
16
		ok(true);
17
	})
18
19
	ajax(function() {
20
		ok(true);
21
		ok(true);
22
	})
23
24
	setTimeout(function() {
25
		start();
26
	}, 2000);
27
})

Conclusion

That's all you need to know to get started witih QUnit. Unit testing is a great method to test your code before publishing it. If you haven't written any unit tests before, it's time to get started! Thanks for reading!

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.