By eidias on (tags: qunit, categories: tools, web)

Another handy javascript lib for your toolbox, but this time, for a slightly different purpose than usual – unit testing

For me, javascript development has always been tied with a sense of uncertainty. I mean, you write the code, check that it works but that’s usually with strong assumptions. What if the DOM element is not there, what if a dependent script is missing.

Well, with unit testing, most of these stay… but, at least we can get rid of a few, and that’s always a good thing.

QUnit is a unit testing framework for javascript – nothing more, nothing less. It allows you to test any logic you write in your scripts and even some UI actions and DOM manipulation.

The process of doing that is not easy – writing the tests themselves is an art of it’s own (and I don’t mean ‘just’ unit tests – I mean javascript unit tests), but after you reach a certain degree of script complexity on your site, it’s good to have a way of knowing if you just introduced a regression bug.

The good news is, that QUnit is dead simple to use. Here’s an basic example from the QUnit page:

   1: <!DOCTYPE html>
   2: <html>
   3: <head>
   4:   <meta charset="utf-8">
   5:   <title>QUnit Example</title>
   6:   <link rel="stylesheet" href="qunit-1.10.0.css">
   7: </head>
   8: <body>
   9:   <div id="qunit"></div>
  10:   <script src="qunit-1.10.0.js"></script>
  11:   <script src="tests.js"></script>
  12: </body>
  13: </html>

and the content of tests.js:

   1: test( "hello test", function() {
   2:   ok( 1 == "1", "Passed!" );
   3: });

Now you run the html page, and get a nice result view:


The red(ish) 0 means that no failures were detected, the green(ish) 1 means that one test has passed, and the black 1 means that one assertion was expected.

QUnit supports synchronous tests, asynchronous tests and various assertions. The docs are pretty decent, there is a coock book available for a quick start and an intro to unit testing to give you a perspective on how this could be used in real life applications.

This type of unit testing may not be as comfortable as unit testing c# apps. You can’t run it on build (or can you?) and just be notified about failures. You have to open a page. The good news is, that after you do that, the results are right there. So, the tool is there, now the hard part – make use of it.