NodeJS testing with Mocha and Should

There are a lot of frameworks to include tests in your projects, one popular choice is Mocha and the Should package for the assertion syntax.

Links:

Mocha Should

Installation

npm install -g mocha npm install should

(-g flag used to install mocha globally so it will be possible to use the mocha executable from anywhere)

Assertions with Should.

Should is a NodeJS module that makes it easy to declare assertions in a kind of natural language. It will throw an exception if the code does not comply with them.

var should = require('should');
var testobj = {
name:"Mary",
age:29,
company:"none",
email:"mary@mary.com",
properties:[
{
"name":"Lake house",
"value":100000
}
]
};
//This should pass (no exception will be thrown)
testobj.should.have.property("name");
testobj.age.should.be.above(20);
testobj.company.should.be.a("string");
testobj.properties.should.not.be.empty;
//This will throw an exception
testobj.properties.length.should.be.within(10,20);

Check the should.js documentation or source for all the features.

Using Mocha and Should

In the following snippet a fake Validator component will be tested

var mocha = require('mocha');
var should = require('should');
//Our fake validation component
var Validator = {
validateName:function(name){
if (typeof name !== 'string')
return false;
if(name.length==0)
return false;
return true;
}
}
//The test suite
describe('Validator',function(){
var testName,valid;
it('should not accept invalid types',function(done){
testName = 123;
valid = Validator.validateName(testName);
valid.should.be.false;
done();
});
it('shoud not accept empty string',function(done){
testName = '';
valid = Validator.validateName(testName);
valid.should.be.false;
done();
});
it('should accept valid strings',function(done){
testName = 'Valid Name';
valid = Validator.validateName(testName);
valid.should.be.true;
done();
})
})
view raw mocha_test.js hosted with ❤ by GitHub

Running the tests with mocha executable

If you invoke mocha from the command line, it will search for a file called tests.js or a directory called tests. You can also specify the name of the test file as:

mocha mytestfile.js

Presenting the results

Mocha has a parameter called ‘reporter’ that allows to get the results in different formats. To list all the avalaible reporters use

mocha --reporters

Using the spec reporter

mocha -R spec mochatest.js

We will get the following:

Mocha results