Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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.

Free Resource

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

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 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) {
            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

It's pretty great.

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

Topics:
mocha ,node.js ,testing

Published at DZone with permission of Emmanouil Gkatziouras, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}