I’m diving into unit testing with Node.js, and my first stop is nodeunit. Luckily, Caolan McMahon wrote an excellent introduction to nodeunit on his blog. Thanks, Caolan.
I installed nodeunit via npm no problem: npm install nodeunit
All the examples in the Installing nodeunit section worked fine, but I needed to addvar events = require('events');
to the first code sample in the Testing asynchronous code section to get those tests to pass. So, the top of my test-doubled.js file looks like:
[sourcecode lang=“javascript”] var doubled = require(’../lib/doubled’); var events = require(’events’); … [/sourcecode]
Farther down in the blog post, in the Shared state and sequential testing section, there’s a code sample with the events include in it, so I think I’m on the right track.
In the Test cases, setUp and tearDown section, I had trouble getting the tests to run. After referencing the project’s README file, I tried adding a callback arg to setUp() and tearDown(), and calling the callback, which worked. So, my code looks like:
[sourcecode lang=“javascript”] …
var testCase = require(’nodeunit’).testCase;
exports.read = testCase({ setUp: function (callback) { this._openStdin = process.openStdin; this._log = console.log; this._calculate = doubled.calculate; this._exit = process.exit;
var ev = this.ev = new events.EventEmitter(); process.openStdin = function () { return ev; };
callback(); }, tearDown: function (callback) { // reset all the overidden functions: process.openStdin = this._openStdin; process.exit = this._exit; doubled.calculate = this._calculate; console.log = this._log;
callback(); }, … [/sourcecode]
With the minor tweaks above, I was able to get all tests to pass:

:)