Using QUnit with Windows 8 Apps

This is an excerpt from the upcoming book Windows 8 Programming with HTML5 for Dummies.

Some of the new research in Windows 8 revolves around using a unit testing framework with your JavaScript, just as if you are writing a JQuery or Node.JS project. Some of those frameworks work well with Windows 8.

For instance, take QUnit as an example. Originally created to be the unit testing environment for JQuery projects, QUnit is now a standalone project. The source can be included in a Windows 8 project, and your tests can get a lot more interesting.

To run tests using QUnit, download the QUnit file and the CSS file from Github (at https://github.com/jquery/qunit) and then put this into your default HTML in your tests file:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Qunit</title>

    <!-- WinJS references -->
    <link href="//Microsoft.WinJS.1.0.RC/css/ui-dark.css" rel="stylesheet" />
    <script src="//Microsoft.WinJS.1.0.RC/js/base.js"></script>
    <script src="//Microsoft.WinJS.1.0.RC/js/ui.js"></script>

    <!-- Qunit references -->
    <link href="/css/default.css" rel="stylesheet" />
    <script src="/js/default.js"></script>
    <script type="text/javascript" src="js/qunit.js"></script>
    <link rel="stylesheet" type="text/css" href="css/qunit.css" />
</head>
<body>
  <div id="qunit"></div>
</body>
</html>

 

tip: Make sure the script source matches.

This gives you a reference point to start your tests. We just need to insert a test into the Windows 8 code. A test looks like this, from the sample website:

    app.onactivated = function (args) {
        if (args.detail.kind === activation.ActivationKind.launch) {
            if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
                test("hello test", function () {
                    ok(1 == "1", "Passed!");
                });
            }
            args.setPromise(WinJS.UI.processAll());
        }
    };

QUnit will give you a nice output on the main page of the Metro app. I just set up a separate page control for testing, and set the default page of the app to it when checking tests.

image

 

 

 

 

That’s all there is to it! Happy testing.

Bill Sempf

Husband. Father. Pentester. Secure software composer. Brewer. Lockpicker. Ninja. Insurrectionist. Lumberjack. All words that have been used to describe me recently. I help people write more secure software.

profile for Bill Sempf on Stack Exchange, a network of free, community-driven Q&A sites

MonthList