Unit testing with Node
An overview of the tools I use daily.
Unit testing is a core skill in your toolbox, and getting it right with Node isn’t hard. Here’s an overview of the tools I use to run my tests.
Mocha
Node is modular, and so is mocha. You can view it as the shell around your tests, handling most things for you. It runs your tests, takes their output and displays the result back in your terminal.
NODE_ENV=test ./node_modules/mocha/bin/mocha —recursive —harmony-generators -R spec

Should
In order to test code, you need to write assertions. Should enables you to write the assertions by extending the Object prototype. This provides an elegant chaining syntax that reads very cleanly.
The ‘describe’ and ‘it’ functions in the example are provided by Mocha.

Supertest
If you ever need to test an API, supertest is there to help. It provides an elegant chaining syntax to test HTTP.
var request = require('supertest');

Attendant
Where supertest is used to test your server code, Attendant has got you for your client code. It provides a configurable mock server with a small-ish API. The example above shows Attendant in action.
Istanbul
Istanbul provides code coverage reports. Hitting 100% code coverage on all branches is something you should aim for when building modules, and Istanbul can help you do that.

External services
If you’re writing unit tests you should definitely consider also using continuous integration (CI) services. Aside from giving you as a maintainer feedback on the project status, they also exhume trust towards users.
I recommend using Travis for CI, and Coveralls for code coverage. Both are free for open source projects, and provide great badges to match their services.
A note on BDD
Behavior driven development is all the rage in the Ruby community, and rightfully so. BDD compliments unit tests by writing features that act as both composable tests and documentation.
Once I’ve sailed a little longer in BDD waters, I’ll share my findings on how to do it properly in Node with you.
Email me when Code & Meta publishes stories
