Wednesday, May 23, 2012

JavaScript unit testing with QUnit

All developers will agree that web development goes hand in hand with client side coding to be able to provide a rich user interface to their users which is prettier, more responsive and impressive. Having that said it should be equally important that we not only unit test our server side code but also client side as well. 
You want to be able to have peace of mind that the user’s experience with your web application will not be one of frustration and complaint when a javascript error not always visible to the user, halted the end result they were expecting.  Which brings me to QUnit, QUnit is jQuery’s popular javascript unit testing framework used by the jQuery, jQueryUi and jQuery mobile projects and was originally developed by John Resig (Father of jQuery).

How 
  1. Download qunit.js and qunit.css.
  2. Create html page and reference the above.
  3. Write your first unit test.
Example
 
<html>
<head>
  <meta charset="utf-8" />
  <title>QUnit example</title>
  <link rel="stylesheet" href="http://code.jquery.com/qunit/qunit-git.css" />
</head>
<body>
  <div id="qunit"></div>
  <div id="qunit-fixture"></div>
  <script src="http://code.jquery.com/qunit/qunit-git.js"></script>
  <script>
      test("Hello world example", function () {
          var value = "hello world!";
          equal(value, "hello world!", "Expected value: hello world!, but was: " + value);
      });
  </script>
</body>
</html>

Pass

Fail

Grouping 

QUnit allows for logical grouping of tests to organise and be able to run individual groups at a time:

module("Group 1");
test("Test 1", function () {
    ok(true, "Pass..");
});
test("Test 2", function () {
    ok(true, "Pass..");
});

module("Group 2");
test("Test 3", function () {
    ok(true, "Pass..");
});
test("Test 4", function () {
    ok(true, "Pass..");
});

Filtering 

QUnit also has the facility to filter and select groups or tests to run:

test.html?filter=group 1 - just the group 1 module
test.html?filter=test 3 - just "test 3"

Use any .NET testing framework and continuous integration servers

Thanks to Robert Moore's Nuget Package we can accomplish just this (more...)

Install-Package NQUnit


Thanks for taking the time to read this post, happy unit testing!


1 comment:

  1. Definitely going to utilize this. Nice post thanks!

    ReplyDelete