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

Podman– Command execution failed with exit code 125

After updating WSL on one of the developer machines, Podman failed to work. When we took a look through Podman Desktop, we noticed that Podman had stopped running and returned the following error message: Error: Command execution failed with exit code 125 Here are the steps we tried to fix the issue: We started by running podman info to get some extra details on what could be wrong: >podman info OS: windows/amd64 provider: wsl version: 5.3.1 Cannot connect to Podman. Please verify your connection to the Linux system using `podman system connection list`, or try `podman machine init` and `podman machine start` to manage a new Linux VM Error: unable to connect to Podman socket: failed to connect: dial tcp 127.0.0.1:2655: connectex: No connection could be made because the target machine actively refused it. That makes sense as the podman VM was not running. Let’s check the VM: >podman machine list NAME         ...

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.

VS Code Planning mode

After the introduction of Plan mode in Visual Studio , it now also found its way into VS Code. Planning mode, or as I like to call it 'Hannibal mode', extends GitHub Copilot's Agent Mode capabilities to handle larger, multi-step coding tasks with a structured approach. Instead of jumping straight into code generation, Planning mode creates a detailed execution plan. If you want more details, have a look at my previous post . Putting plan mode into action VS Code takes a different approach compared to Visual Studio when using plan mode. Instead of a configuration setting that you can activate but have limited control over, planning is available as a separate chat mode/agent: I like this approach better than how Visual Studio does it as you have explicit control when plan mode is activated. Instead of immediately diving into execution, the plan agent creates a plan and asks some follow up questions: You can further edit the plan by clicking on ‘Open in Editor’: ...