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() {
        assert(true)
    })
})

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:"www.google.com",path:"/"},function(result) {
        result.on('end',function() {
            done()
        })    
    })

    request.on('error',function(e) {
        done(e)
    })
 
    request.end()
})

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) {
            done(err)
        } else {
            connection = db
            done()
        }
    })
})

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