Skip to content

Unit Testing with Nodeunit

MikeKlemarewski edited this page Jun 20, 2012 · 2 revisions

Nodeunit tests exports from a file. You can group test cases into groups, which share setUp and tearDown functions. The setUp and tearDown functions are called at the start and end of every test. Use them to set up anything that will be shared between tests.

module.exports = {
	groupName: {
		setUp: function(callback){
                        //set up stuff
                        callback();
		},

		tearDown: function(callback){
			//tear down stuff
			callback();
		},

		"Test 1": function(test){
                        test.ok(true);
                        test.done();
		},
		"Test 2": function(test){
                        test.strictEqual(someVal, "match");
                        test.done();
                 },
}

Potential problems

When creating a server for a group or tests, it's a good idea to create a fresh server for each test to ensure there are no residual effects from a previous test. You cannot simply start and stop the server. You must create a new instance of the server in the setUp and tearDown functions.

setUp: function(callback){
	this.server = express.createServer();
	this.server.use(server)
	this.server.listen(config.port);
	this.server.on("listening", callback);
},

tearDown: function(callback){
	this.server.close();
	callback();
},
Clone this wiki locally