I’ve been incorporating more JavaScript into my Webapps lately, and have finally take some time out to have a look at some Unit Testing options for JavaScript. There’s quite a few solid libraries to look at including JSUnit, YUITest and QUnit (and many more BDD ones emerging), so the whole experience can be a little daunting at the start.
For my particularly used case, I wanted something very lightweight and easy to integrate into my existing framework. I ended up going with QUnit, basically because it was (a) simple; (b) popular; (c) consisted of two files; and (d) had plenty of “getting started” articles I could template off. I’ve been very happy with it so far.
If you have JUnit background and are curious what a JavaScript testing library looks like, check out a sample test:
test("You can't handle the truth", function() { var someTrueExpression = true; ok( someTrueExpression, "True expressions" ); }); test("Equals, and not so much", function() { var actual, expected; actual = expected = 2; equal(expected, actual, "Basic comparison" ); notEqual(expected, 3, "Asserting not equals"); });
One thing I really like about QUnit is that it makes things very easy to get started. Basically you create a html file with elements for each of the test results, and QUnit looks after the runner and markup of the output. Just add a single QUnit.js file and a supporting QUnit.css and you have a:
So what does a complete QUnit test page look like? Here’s something you can cut and paste and get started:
# Basic QUnit Demo ## ##test markup
JavaScript has some special language support around equality (the string example is a classic since 2 == “2” in JavaScript, but 2 !== “2”). So you can do strict and non-strict equality:
test("Equals edge cases", function() { equal("2", 2, "Equals are not strict"); // but this will fail... strictEqual("2", 2, "Strict type equals"); });
There’s also great support for test suites with the standard setup() and teardown() type functions you’re used to:
module("Control Flow", { setup: function() { console.log("Just some setup stuff") }, teardown: function() { console.log("Just some teardown stuff") } });
There’s also support for exception assertions that can be pretty handy:
test("Exceptional stuff", function() { raises(function() { throw new Error("World of pain"); }, "Ensure error is thrown"); });
There’s certainly plenty to learn around the async parts of JavaScript (such as unit testing Ajax calls), and that’s next on my list for exploration (along with automated test runners for JavaScript testing).
But if you’re after a first exposure to how JavaScript unit testing libraries hang together, QUnit is definitely worth a look! Great stuff!