Skip to main content

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" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <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>
</head>
<body>
 <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>
</body>
</html>


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 () {
  Calculator.add(1);
 }, "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:
image


If you want to know more about the QUnit basics, I can recommend the following tutorial(http://net.tutsplus.com/tutorials/javascript-ajax/how-to-test-your-javascript-code-with-qunit/). 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) {
            completedHandler(result);
        });

        post.fail(function () {
            completedHandler('error');
        });
    };

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:

image


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
            stop(1000);

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


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.
image

Popular posts from this blog

Azure DevOps/ GitHub emoji

I’m really bad at remembering emoji’s. So here is cheat sheet with all emoji’s that can be used in tools that support the github emoji markdown markup: All credits go to rcaviers who created this list.

Kubernetes–Limit your environmental impact

Reducing the carbon footprint and CO2 emission of our (cloud) workloads, is a responsibility of all of us. If you are running a Kubernetes cluster, have a look at Kube-Green . kube-green is a simple Kubernetes operator that automatically shuts down (some of) your pods when you don't need them. A single pod produces about 11 Kg CO2eq per year( here the calculation). Reason enough to give it a try! Installing kube-green in your cluster The easiest way to install the operator in your cluster is through kubectl. We first need to install a cert-manager: kubectl apply -f https://github.com/cert-manager/cert-manager/releases/download/v1.14.5/cert-manager.yaml Remark: Wait a minute before you continue as it can take some time before the cert-manager is up & running inside your cluster. Now we can install the kube-green operator: kubectl apply -f https://github.com/kube-green/kube-green/releases/latest/download/kube-green.yaml Now in the namespace where we want t

DevToys–A swiss army knife for developers

As a developer there are a lot of small tasks you need to do as part of your coding, debugging and testing activities.  DevToys is an offline windows app that tries to help you with these tasks. Instead of using different websites you get a fully offline experience offering help for a large list of tasks. Many tools are available. Here is the current list: Converters JSON <> YAML Timestamp Number Base Cron Parser Encoders / Decoders HTML URL Base64 Text & Image GZip JWT Decoder Formatters JSON SQL XML Generators Hash (MD5, SHA1, SHA256, SHA512) UUID 1 and 4 Lorem Ipsum Checksum Text Escape / Unescape Inspector & Case Converter Regex Tester Text Comparer XML Validator Markdown Preview Graphic Color B