a blog for those who code

Friday, 24 March 2017

How to test Node.js Application using Mocha

In this post we will be discussing about testing Nodejs application using Mocha. We all know that testing is an important practice in software development, which will improve the quality of the software. Here in this post we will show a simple, quick and effective way to build and unit test your Node.js application.

We will be using Mocha which is a JavaScript test framework which maps uncaught exception to the correct test cases. The purpose here is that whatever functionality we have written should pass the test cases. The Node.js application which will be using is dead simple where we have two methods i.e. get : to get all the todos and save : to save a new todo value.


var fs = require('fs');
module.exports = {
 todos : {
  get: function() {
   var data = fs.readFileSync('./todos.json', 'utf-8');
   return JSON.parse(data);
  save: function(todo) {
   var data = fs.readFileSync('./todos.json', 'utf-8');
   var todos = JSON.parse(data);
   fs.writeFileSync('./todos.json', JSON.stringify(todos));

Next we will write a test case using mocha. We have to create a test folder inside our application and then we have created test.js file to write the test cases. In the below test we have used describe function which is used to set up a group of test with a name (in our case it is dataTest). Then we have a it function which is given a description of what the test is doing and then the second argument will contain the assertions using should.js.

var should = require('should');
describe('dataTest', function() {
 var data = require('../data.js');
 it('todo count should increase by 1', function () {
  var todos = data.todos.get();
  data.todos.save({todoName : 'Write Coding Defined 1st Post'});
  var latestTodos = data.todos.get();
  latestTodos.length.should.equal(todos.length + 1);

After that you should run mocha in the command prompt which will by default run everything in /test folder. After running you will see the result as shown below :

In this post we have looked at a practical example of unit testing in Node using Mocha testing framework and using should as assert. In our next post we will include the testing of a Rest API using Mocha, Should.js and Supertest.

Please Like and Share the CodingDefined.com Blog, if you find it interesting and helpful.

No comments:

Post a Comment