Software QA FYI - SQAFYI

Tools to unit test your JavaScript


Unit testing focuses on verifying that a module or a unit of code is working as designed or as expected. Some developers, who would rather spend time implementing new modules, consider writing test cases a waste of time. When dealing with large applications, however, unit testing actually saves time; it helps you track issues and lets you safely update your code.

In the past, unit testing was applied only to server-side languages. But, the increasing complexity in front-end components has increased the need for writing test cases for JavaScript code. The learning curve can be steep if you do not typically write tests for client-side scripting. Testing the user interface might require adjustments in your thought process. (And, some developers may still have a hard time believing that JavaScript is a proper programming language.)

In this article, learn how to use QUnit, YUI Test, and JSTestDriver to unit test JavaScript.

JavaScript unit testing

To illustrate JavaScript testing, this section analyzes a test case for a basic function in JavaScript. Listing 1 shows the function to be tested: add 3 (as a number) to the variable passed.

Listing 1. Source code (example1/script.js)

function addThreeToNumber(el){
return el + 3;

Listing 2 contains the test case in a self-executing function.

Listing 2. Test case (example1/test.js)

(function testAddThreeToNumber (){
var a = 5,
valueExpected= 8;

if (addThreeToNumber (a) === valueExpected) {
} else {

After passing 5 to the function being tested, the test checks that the return value is 8. If the test is successful, Passed! is printed in the console of a modern browser; otherwise, Failed! appears. To run this test, you need to:

1. Import the two script files in an HTML page that will act as a test runner, as shown in Listing 3.
2. Open the page in your browser.

Listing 3. HTML page (example1/runner.html)
<!DOCTYPE html>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Example 1</title>
<script type="text/javascript" src="js/script.js"></script>
<script type="text/javascript" src="js/test.js"></script>

Instead of using the browser console, you could print the results inside the page or inside pop-up windows generated by the alert() method.

Assertions, which are the core elements in test cases, are used to verify that a certain condition is satisfied. For example, in Listing 2, addThreeToNumber (a) === valueExpected is an assertion.

If you have a lot of test cases with many assertions, a framework comes in handy. The following sections highlight some of the most popular JavaScript unit testing frameworks: QUnit, YUI Test, and JSTestDriver.

Full article...

Other Resource

... to read more articles, visit

Tools to unit test your JavaScript