Getting started with unit testing for Node.js

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 add
var 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:

var doubled = require('../lib/doubled');
var events = require('events');
...

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:

...

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();
},
...

With the minor tweaks above, I was able to get all tests to pass:
Screenshot of all tests passing

๐Ÿ™‚

3 thoughts on “Getting started with unit testing for Node.js

  1. I’m stuck for a while following Caolan’s blog as well.
    Same as you, I got to know that I have to explicitly invoke callback in setUp and tearDown. I don’t know why they set API like this.
    IMHO, there is no arguments to callback. Why not just have the system trigger it? For asynchronous? I don’t understand.

  2. Thank you very much! I had exactly the same problem and didn’t wanted to quit from that great blog with errors ๐Ÿ˜€

Comments are closed.