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.
Following are the tests for the MyMath module.
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
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
}); | |
}) | |
}); |
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