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.

Cache stampede: when our cache turned against us

While investigating some performance issues, we ran into an ASP.NET Core API that cached a fairly expensive aggregation query for 60 seconds. Under normal load, that was fine: one request rebuilds the cache, everyone else reads from it. Under peak load, dozens of requests would arrive in that same expiry window, all see a cache miss, and all fire the same expensive query in parallel. The database didn't like that. That was the moment when our caching layer stopped helping and started hurting. A burst of requests comes in at the same time, all miss the cache, and all go hammer the database or the downstream API at once. That's a cache stampede . The cache was supposed to protect our backend, and for a few hundred milliseconds it did the opposite. Why this happens IMemoryCache.GetOrCreate (and its async sibling) looks like it protects you, but it doesn't add any locking on its own. Look at the naive version: public async Task<Report> GetReportAsync(string key) ...