How to write NodeJS Unit Test

I wasn’t a big fan of unit tests during college since the project scope are so tiny that writing them became really dumb and repetitive. But now that the requirements and logic for my projects have become a lot more complex, unit test is actually really useful. NodeJS itself has an assert module that is used to write unit test. The reason I’m writing this post is that doing some googling didn’t help me much when I first started writing those. Some of the articles were also outdated. I’m sure this one will also but I’ll try to keep it updated.

So u wanna test your server? Here’s how to do it. The code below was used to unit test my JSON-RPC server. I started with importing the modules:

var http = require('http');
var assert = require('assert');
var jrpcs = require('./jrpc');
var options = {
   host: 'localhost',
   port: 3000,
   method : 'POST'
};

In order to test my server, I have to fire it up:

var server = http.createServer(function(req, res) {
   jrpcs.handle(req, res);
});

Now the tricky part is here: Since everything is callback, invoking tests after calling createServer doesn’t guarantee the server is initialized. The trick is to put test request inside listen:

server.listen(3000, 'localhost', function() {
   var req = http.request(options, function(res) {
      console.log('Test empty body POST request');
      checkBadResponse(res);
      server.close();
   });
   req.end();
});

So that guarantee that when I fire my test request, server is definitely up. Once I got my response and check everything, I close my server. I do that right away cause I only had 1 tests but if you have have more than 1, this has to be coordinated.

Anw, just a quick blog post on how to write unit test in NodeJS.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: