Mocha and Node.js

Mocha is my choice of testing framework when it comes to node.js.

We should add it as a dependency on package.json

  "dependencies": {
    "mocha": "~2.2.4",

Our test would be mocha-example-test.js

var assert = require('assert');

describe('Mocha Example',function(){
    it('Plain Check',function() {

We can handle asynchronous code with the done callback

var http = require('http')

it('Asynchronous Example with http connection',function(done) {
    var request = http.request({host:"",path:"/"},function(result) {
        result.on('end',function() {

    request.on('error',function(e) {

Also we can issue action before each test executes or before the execution of the test suite

For example we open a Mongodb connection before test cases being executed.

var MongoClient = require('mongodb').MongoClient

var connection

before(function(done) {
    MongoClient.connect(url,function(err,db) {

        if(err) {
        } else {
            connection = db

Before each test case we set up the mongodb collection that will be used.

var collection
beforeEach(function() {
    collection = connection.collection('example')

In order to run a mocha test we just issue

./node_modules/mocha/bin/mocha mocha-example-test.js

Leave a Reply

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

You are commenting using your 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