Friday, 21 October 2011

QUnit: TDD with JavaScript


QUnit is a TDD framework that allows developers to write unit tests against their JavaScript libraries and run them in the browser or against a CI server. 

For this blog article I’ll be showing you how to setup your dev machine to write and run the tests.

What shall we Unit Test today?

For this example I am going to create some unit tests around a popular jQuery pub/sub plugin, which is available here:

The plugin API is very simple and allows the developer to: 

  • subscribe to an topic
  • unsubscribe from a topic
  • publish a topic

My Folder and File Layout for QUnit


When you download the source code to my example you’ll see the following files:

core Folder Contains the two core libraries to run QUnit:  QUnit.js and QUnit.css
(JQuery is also required, online file used)
source Folder Contains the JavaScript you will be testing
tests Folder The unit tests
TestRunner.html Folder Open in the browser to run the tests

This layout is purely my preference but helps me keep a nice structure to my tests and CI build.

The Test Runner

The Tests

The first couple of lines are just const variables for topics and can be ignored. 

module("Pub/Sub Tests"); gives the tests a grouping (see test output image at the top of the blog article.

test("test name”, function () { … }); is the unit test name and code.

expect(1); states the number of expected assertions within the test.  If this number is not realised the test will fail.

ok(error === null, 'No error occurred'); and equal(count, 2, 'callback was fired twice'); are examples of assertions.


My example source code:

QUnit source:

QUnit docs:

No comments:

Post a Comment