Friday, May 4, 2012

Async Ajax testing using QUnit

Testing Javascript code is not that hard, but as most Javascript functionality contains some level of asychronity, testing becomes a lot harder. Let’s have a look at how we can tackle this problem.
Although other testing frameworks are available, I’m using QUnit, a powerful JavaScript unit testing framework written by members of the jQuery team.
QUnit Introduction
So how do you write unit tests with QUnit exactly? First, you need to set up a testing environment. Create an html file with the following content:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="" >
    <title>My Tests</title>
    <script src="../Scripts/jquery-1.7.2.js" type="text/javascript"></script>
    <link href="../Content/qunit.css" rel="stylesheet" type="text/css" />
    <script src="../Scripts/qunit.js" type="text/javascript"></script>
    <!--Add your project files-->
 <script src="../Scripts/calculator.js" type="text/javascript"></script>
 <!--Add your test files-->
 <script src="../Scripts/calculatortests.js" type="text/javascript></script>
 <h1 id="qunit-header">My Tests</h1>
 <h2 id="qunit-banner"></h2>
 <div id="qunit-testrunner-toolbar"></div>
 <h2 id="qunit-userAgent"></h2>
 <ol id="qunit-tests"></ol>
 <div id="qunit-fixture">test markup, will be hidden</div>

Let’s now have a look at the calculatortests.js.

module("Add Module");

test("Add should add 2 items", function () {
 var result = Calculator.add(1, 2);
 equal(result, 3, "Result of 1+2 should be 3");

test("Add should fail if one item is missing", function () {
 raises(function () {
 }, "Incorrect number of arguments");

Tests are created by calling the test() function, 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. Test cases can be organized into different modules by calling the module function.
Let’s have a look at the output if we browse to the created html file:

If you want to know more about the QUnit basics, I can recommend the following tutorial( But we should continue and have a look at the async testing functionality.
Async testing
In the calculator object I was testing before I had the following method to add two values:
that.add = function (a, b) {
        if (arguments.length != 2)
            throw new Error("The number of arguments is incorrect");
        return a + b;

Let’s now add another method that doesn’t calculate the sum on the client but let the server do all the work:
 that.remoteAdd = function (a, b, completedHandler) {
        var post = $.ajax({
            url: "/Calculator/Add/",
            data: { a: a, b: b },
            type: "POST"

        post.done(function (result) {
        }); () {

This time I’m passing an extra argument; the completedHandler that will be invoked when the Ajax call has completed. Let’s first try to write the test case in a synchronous fashion:
  test("Remote add should also add 2 items", function () {
            var result = 0;

            Calculator.remoteAdd(1, 2, function (r) {
                result = r;

            equal(result, 3, "Result of 1+2 should be 3");

But if we run the test, it fails because the test execution completed before the Ajax call returns and the completedHandler is invoked:


To make this test pass, we’ll have to change it into an asynchronous test. QUnit provides us 2 helper functions for this:
  • stop(): allows you to pause the assertions for a specified time interval
  • start(): allows you to continue test execution
Let’s see these two functions in action:
  test("Remote add should also add 2 items", function () {
            var result = 0;
            //Wait 1 sec before looking at the results

            Calculator.remoteAdd(1, 2, function (r) {
                result = r;
                equal(result, 3, "Result of 1+2 should be 3");
                //Continue the test execution

Stop() will not stop the test execution but will postpone the assertion(the equal check in this case) until the time interval has expired. This gives the AJAX call enough time to get the result from the server and invoke the completedHandler.

1 comment:

Anonymous said...

test("An async test", function(){
expect(1); {} , {
success : function(model,resp){
ok(model.get('id') != null, "Got id");

I still get the error.

Expected at least one assertion, but none were run - call expect(0) to accept zero assertions.
Please give me a solution.