Blog Archives

Two new QUnit Test Types – Skipped and Interactive

I love unit testing, and the confident feeling I get from my code being “all green”. But sometimes there are tests that need to be skipped for a bit, perhaps due to a failing backend service or an in-progress refactoring. The easiest solution is to comment them out, but then it’s easy to forget they are being skipped. Instead, I simply added a new test type – testSkip – to QUnit using the following code. Now when the test is skipped we see it marked as SKIPPED in the QUnit results.


QUnit.testSkip = function() {
   q.test(arguments[0] + " (SKIPPED)", function() {});
};

I use a similar approach for QUnit tests that involve user interaction. I run lots of tests when coding, but the interactive ones get in the way of my flow. So I have added the test type testManual which allows me to run them explicitly by simply adding testmanual to the URL parameters. A similar approach can be used for other test categories or to target tests to a particular browser.


QUnit.testManual = function() {
   if(/(\?|&)testmanual($|&|=)/.test(window.location.href)) {
      q.test.apply(q, arguments);
   } else {
      q.testSkip.apply(q, arguments);
   }
};

Advertisement

Logging QUnit results

I’ve mentioned QUnit in other posts [POST: CUSTOM QUNIT TEST TYPES] and how much stock I put into unit testing in general, so I thought I’d share some more tips for people who don’t have much experience with QUnit. This will probably be a recurring theme on this blog.

One of the advantages of QUnit is that it has built-in hooks for testing automation tools. I use these hooks to do basic console logging so I can see what test is running next to my own log messages. I also log the amount of time each test takes.

The code to add these hooks is straightforward:

var startTime = null;
var currentTest = null;
QUnit.testStart = function(details) {
   currentTest = details.name;
   startTime = new Date().getTime();
   console.warn("QUnit starting " + currentTest);
};

QUnit.testDone = function(details) {
   console.assert(currentTest);
   cm.console.warn("QUnit finished " + currentTest + " (" + (new Date().getTime() - startTime).toString() + " ms)");
   currentTest = null;
};

QUnit.begin = function(details) {
   cm.console.log("QUnit starting");
};

QUnit.done = function(details) {
   cm.console.log("QUnit finished");
};

If you use modules then there are hooks at that level also:

QUnit.moduleStart = function(details) {
};
QUnit.moduleDone = function(details) {
};

The same approach can be used to do other things like send notifications (email/tweet) or generate a timing summary. You can read more about the QUnit integration hooks at:
http://docs.jquery.com/Qunit#Integration_into_Browser_Automation_Tools.

%d bloggers like this: