Unit testing with JavaScript and NodeJS
October 6, 2011 2 Comments
In my latest project I needed a way to execute JavaScript from the command line. I knew a little about the Rhino project which achieves this and of course the Google V8 Project.
I experimented a little with V8 and the default shell sample application that it ships with. I found it easy to introduce native functionality using C++ and this seemed to perform well. I then discovered the nodejs project. nodejs is built on top of V8 and includes lots of general purpose functionality which is great for running JavaScript from the command line and fantastic for developing server applications.
Instead of reinventing the wheel with my custom V8 shell I decided to use nodejs. nodejs has an excellent module system which makes it easy to add new functionality.
Unit testing is important because it helps us to develop code of a high quality. I tend to use QUnit from the jQuery project to perform unit testing on client JavaScripts. Whilst QUnit may not be the most comprehensive unit testing library, it is very easy to use and provides detailed output.
It is now necessary to develop unit tests for command line and server application JavaScripts. Unfortunately the regular QUnit framework cannot be used because it requires the DOM to report feedback. Fortunately the node-qunit module can be added to nodejs which adds support for QUnit style unit testing.
Whilst there are notable differences between the way in which these two QUnit variants behave, it is possible to write unit tests that are compatible with both versions. For example, `QUnit.module` should be used instead of `module` because `module` means something different in nodejs.

I like Jasmine [1] for this purpose, which can also be installed as a module [2] via the Node Package Manager.
[1] http://www.2ality.com/2011/10/jasmine.html
[2] https://github.com/mhevery/jasmine-node
Hello Axel
Jasmine looks like a really good unit testing framework. I am going to have a play with it over the weekend!
Cheers