Sunday, April 14, 2013

Node.js testing with Mocha and should.js

I noticed that i was doing a lot of exploratory testing in node.js. I wanted to checkout how easy/difficult would it be TDD. This is what i found. There is a decent testing framework called Mocha.

Testing node.js modules with Mocha Following is the module under test, which is just there as a test really. My barebones math class is below.

MyMath = function MyMath(seeddata) {
var seedvalue = 0;
seedvalue = seeddata;
function _add(x,y) {
return x + y + seedvalue;
}
function _multiply(x,y, callback) {
setTimeout(function() {
console.log("Timer has fired now");
callback(x*y);
}, 5000);
}
return {
add : _add,
multiply : _multiply
};
}
exports.MyMath = MyMath
view raw gistfile1.txt hosted with ❤ by GitHub
Following are the tests for the MyMath module.
var mymathvar = require('./mymath');
var should = require('should');
var mymath;
beforeEach(function() {
mymath = new mymathvar.MyMath(10);
})
describe('add', function() {
it('Should add 2 numbers and return the result', function() {
mymath.add(10,20).should.equal(40);
})
})
describe('add()', function() {
it('Shoud add zero correctly', function() {
mymath.add(0,10).should.equal(20);
})
})
describe('multiply()', function() {
it('Should multiply numbers as per the math', function() {
mymath.multiply(10,20, function(total){
total.should.equal(210);
done();
});
})
});
view raw mymathtest.js hosted with ❤ by GitHub
Neat and simple. I have used the should module to do the assertions.

Finally, this is how you can run the tests using mocha.


 

To install Mocha and should you could use the Node package manager.To read further please head to Mocha

No comments:

Post a Comment

Followers

About Me

I'm a software developer with interests in Design Patterns, Distributed programming, Big Data, Machine Learning and anything which excites me. I like to prototype new ideas and always on the lookout for tools which help me get the job done faster. Currently, i'm loving node.js + Mongodb.