Learn Unit Testing With Nodejs

In this tutorial we are going to talk about unit testing of our applications, So this tutorial is very important for each developer to make high standard applications.

If we are planning to create any product then we must ensure one thing in mind is testing of the product because testing makes your product more stable & bug free.

So Here you will learn some basic methods of unit testing using nodejs.

First of all you need to know, What is Unit Testing?
Unit testing is a software development process in which the smallest testable parts of an application, called units, are individually and independently scrutinized for proper operation. Unit testing is often automated but it can also be done manually.

But here we’ll talk about the automated test methods of the application.



I have created a very small application in nodejs which connect with the mysql database and fetch data from mysql table.
http://www.iamrohit.in/nodejs-with-mysql-connectivity-example/

Here I have used nodeunit module to write the automated unit test methods in nodejs to test mysql connectivity and count table rows.

Step-1: Install nodeunit in your system

sudo npm install nodeunit -g

Step-2: Create your unit test file in your project directory.

unittest.js

include required libraries for your project

var express    = require("express");
var mysql      = require('mysql');
var app = express();

Step-3: Configure mysql credentials

var connectionInfo = {
  host     : 'localhost',  
  user     : 'root',       
  password : 'root',       
  database : 'node_mysql'  
}
var connection = mysql.createConnection(connectionInfo);

Step-4: Write your first unit test to check mysql connectivity.


exports.testMySqlConnectivity = function(test){
     connection.connect(function(err){
         if(err) {
            test.ok(false, "Error to connect database.");
          } else {
            test.ok(true, "Database connected successfully.");
          }
          test.done();
     }); 
};

Where .ok(value, [message]) – Tests if value is a true value.

Step-5: Write another test to check rows count of the table.


exports.testRowsCount = function(test){
     var query = 'SELECT * FROM posts';
        connection.query(query, function(err, rows, fields) {
            var expectedRows = 2;
            var actualRows = rows.length;
            connection.end();
             if(err) {
                test.ok(false, "Error to execute query.");
             } else {
                test.equal(
                    actualRows, 
                    expectedRows, 
                    "Actual result is: "+actualRows +", Expected result is: "+expectedRows
                );
 
             }
             test.done();
 
     }); 
 
};

where .equal(actual, expected, [message]) – Tests shallow, coercive equality with the equal comparison operator ( == ).

Now your final unittest.js file will be..

unittest.js

var express    = require("express");
var mysql      = require('mysql');
var app = express();
 
var connectionInfo = {
  host     : 'localhost',  
  user     : 'root',       
  password : 'root',       
  database : 'node_mysql'  
}
 
var connection = mysql.createConnection(connectionInfo);
 

exports.testMySqlConnectivity = function(test){
     connection.connect(function(err){
         if(err) {
            test.ok(false, "Error to connect database.");
          } else {
            test.ok(true, "Database connected successfully.");
          }
          test.done();
     }); 
};
 
 

exports.testRowsCount = function(test){
     var query = 'SELECT * FROM posts';
        connection.query(query, function(err, rows, fields) {
            var expectedRows = 2;
            var actualRows = rows.length;
            connection.end();
             if(err) {
                test.ok(false, "Error to execute query.");
             } else {
                test.equal(
                    actualRows, 
                    expectedRows, 
                    "Actual result is: "+actualRows +", Expected result is: "+expectedRows
                );
 
             }
             test.done();
 
     }); 
 
};
 
console.log("Listening  on 5000");
app.listen(5000);

Step-6: Now time to run your test cases.

cd YourProjectDirectory
nodeunit tests/unittest.js

In case of test success output will be.
unittest-1

In case of test failure output will be
My database table has 2 rows but i assigned expected value = 4 then test failure output will be.
unittest-2

I hope this tutorial will help you to write unit testing in nodejs. you can learn more about nodeunit from https://github.com/caolan/nodeunit And download sample code from my github repository.

If you like this post please don’t forget to subscribe My Public Notebook for more useful stuff.