Over a million developers have joined DZone.

Why I Use Mocha For Testing in Node.js

DZone's Guide to

Why I Use Mocha For Testing in Node.js

Mocha is a testing framework for Node.js that can handle asynchronous code. See some code snippets demonstrating its strengths.

· Web Dev Zone ·
Free Resource

Access over 20 APIs and mobile SDKs, up to 250k transactions free with no credit card required

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

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


Also we can issue actions 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

It's pretty great.

#1 for location developers in quality, price and choice, switch to HERE.

mocha ,node.js ,testing

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}