O'Reilly logo

JavaScript Cookbook by Shelley Powers

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

17.2. Testing Your Code with JsUnit

Problem

You followed the good structuring practices outlined in Recipe 17.1 to create your JavaScript objects. Now you want to thoroughly test your code before packaging it into a library for distribution.

Solution

Use a tool like JsUnit to create test cases to formally test your library. If your library contains an object method like the following:

function addAndRound(value1,value2) {
    return Math.round(value1 + value2);
}

JsUnit test cases could look like the following:

function testAddAndRound() {
    assertEquals("checking valid", 6, addAndRound(3.55, 2.33));
    assertNaN("checking NaN",addAndRound("three",
"Four and a quarter"));
}

Both tests would be successful: the first because the result of the function is equal to the value 6, and both results are numbers; the second because the result of the function call is NaN, which is what the test checks.

Discussion

Chapter 10 covered error handling and debugging using a variety of tools, depending on your preferred development browser. Now, you’re ready to create more formal tests, not only for your own use, but for others. These types of tests are called unit tests.

A good rule of thumb when it comes to unit testing is that every requirement or use case for a library function (or object method) should have an associated test case (or cases). The unit test checks that the requirement is met, and the library function performs as expected. You can develop your own tests, but using something like JsUnit simplifies the test writing.

Note

The version of JsUnit I use is a JavaScript implementation of the well-known JUnit testing software, and was developed by Edward Hieatt. JsUnit can be downloaded at http://www.jsunit.net/, which also includes links for documentation and examples.

Once you’ve downloaded, unzipped, and installed the JsUnit folder, preferably in a test folder for your own application, create several test application pages to test your library’s functionality. Each page will contain a link to the JsUnit engine and your library. If the JsUnit library is located in its folder direction in your development subdirectory, link it as follows:

<script type="text/javascript" src="app/jsUnitCore.js"></script>
<script type="text/javascript" src="lib/myLibrary.js"></script>

Use the JsUnit methods in script in the page to perform the tests, and the JsUnit web page, testRunner.html, to actually run the test. How the test functions are written are based on JUnit testing methodology: the function names begin with test and can have no parameters.

The JsUnit assertions used to write tests are:

assert ([comment],booleanValue)

Tests that a function returns a Boolean value.

assertTrue([comment],booleanValue)

Tests for true return.

assertFalse([comment], booleanValue)

Tests for false return.

assertEquals([comment], value1, value2)

Tests return result or variable for equality.

assertsNotEquals ([comment],value1,value2)

Tests return result or variable against another value for nonequality.

assertNull([comment],value)

Tests for null value or return.

assertNotNull([comment],value)

Tests for nonnull value or return.

The first parameter in the functions—the comment—is optional. However, it does make it much easier to determine which test fails if you can see a unique comment for the test.

JsUnit supports other functions, such as setUp and tearDown, called before the tests are started and after they have finished, respectively. There are also three functions, which provide trace messages:

warn(message,[value])

Warning message, with optional value

inform(message,[value])

Information message, with optional value

debug(message,[value])

Debugging information, with optional value

Once you’ve created your test page, you run the tests within the testRunner.html page. If some of the tests fail, errors will display under the test progress bar. If you double-click the test, you can get the test fail information, as shown in Figure 17-1.

To see the JsUnit functionality in action, Example 17-1 contains a simple object with three methods.

Example 17-1. Simple JavaScript object with methods

var BBTest = {
  concatWithSpace : function(string1, string2) {
    return string1 + " " + string2;
  },
  discoverNumber : function(string, number) {
    return string.indexOf(number);
  },
  divideNumbers : function (value1, value2) {
    return value1 / value2;
  },
  addAndRound : function(value1, value2) {
    return Math.round(value1 + value2);
  }
}

Example 17-2 is a JsUnit test page that tests the object methods.

A JsUnit test run with some failed tests

Figure 17-1. A JsUnit test run with some failed tests

Example 17-2. JsUnit Test page to test methods for object in Example 17-1

<!DOCTYPE html>
<head>
<title>Testing Library</title>
<script src="jsunit/app/jsUnitCore.js"></script>
<script src="test.js"></script>
<script>

function testConcatWithSpace() {
  inform("Testing concatWithSpace");
  assertEquals("Checking equality", "Shelley
Powers",BBTest.concatWithSpace("Shelley","Powers"));
}

function testDiscoverNumber() {
  inform("Testing discoverNumber");
  assertEquals("Checking valid params",5,
BBTest.discoverNumber("found5value",5));
}

function testDivideNumbers() {
  inform("Testing divideNumbers");
  assertNaN("Checking numeric ops with no numbers",
BBTest.divideNumbers("five","2"));
  assertNotEquals("Checking not equals","5",
BBTest.divideNumbers(10,2));
}

function testAddAndRound() {
  inform("Testing addAndRound");
  assertNaN("Checking NaN",BBTest.addAndRound("four",
"Three Quarter"));
  assertEquals("Checking correct values",6,
BBTest.addAndRound(2.33,3.45));
}

</script>

</head>
<body>
<p>Running tests of test.js. View source to see tests.</p>
</body>

Load the test page into the testRunner.html page, located within the jsUnit subdirectory. All of the tests are successful, as shown in Figure 17-2.

Successful run of test page in

Figure 17-2. Successful run of test page in Example 17-2

JsUnit can be managed manually, or can be integrated into an automated testing environment, including integration with Apache Ant.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required