Click here to Skip to main content
15,881,413 members
Articles / DevOps / Unit Testing
Tip/Trick

Easy Error Mocking in node.js/mocha

Rate me:
Please Sign up or sign in to vote.
4.67/5 (2 votes)
21 Nov 2013CPOL3 min read 12.8K   34   1  
Easy error mocking in node.js/mocha/istanbul to achieve full code coverage

Introduction

Writing unit tests for node.js code is very important, it is almost a mandatory action. I use mocha to do my unit testing. I also use Istanbul to do my code coverage reports.

Naturally, one would want to cover as much code as possible. Few branches are hard to cover, namely those branches that handle fatal errors, for example, fatal errors that come from MongoDB drivers, like when network connectivity is lost. I wanted an easy, fast and simple way to cover those branches. My previous article describes how to create a proxy pattern in JavaScript. I am going to use that same proxy pattern here to add a proxy to the objects that I want them to throw mocked errors.

Creating the Error Mocker Proxy

In my previous article, there is a generic JavaScript proxy pattern. I am going to use that pattern to create an error mocker. The proxy function modifies a class by taking its constructor and rewiring each function to a new function. This new function will properly call before/after events along with the original function of the class. The before/after events in this case will be functions that will check for error mocking, if error mocking is required, an error is thrown (or sent via callback).

Once you use the error mocker function on a class, two new functions are added to it:

JavaScript
mockfailAfter(count, throwException) {...}

and:

JavaScript
mockfailOnFunctionName(fname, throwException) {...}

mockfailOnFunctionName takes a function name, in this case, you type in the function name that should fail the next time it is called. throwException is a boolean to indicate how you want this function to fail, if set to true, an exception is raised, if set to false, a callback function should exist which will be called with an error. The use of mockfailAfter function is a little different, instead of giving it a function name, you give it a count, this count is decremented every time any function of the target class is called, once it hits zero, it will mock the error then. Those two functions were all I needed at the time of writing this article, however you can easily add more functions (file ErrorMocker.js) that are suited for your needs. For example, you could create a function that combines failing on a function name and a count of calls of that function name, or possibly a function name and a particular value for an argument of that function...

Using the Code

Since this article is targeted at node.js environment, you can download the files and use them right away. The two main files you need are proxy.js and ErrorMocker.js. If you need them for other JavaScript uses, you might need to modify them a little.

In your unit testing file, you require ErrorMocker.js:

JavaScript
var ErrorMocker = require("./ErrorMocker.js");  

And for each class that you want to mock errors on, you have to attach the proxy pattern to it, usually you do this in the before section of Mocha, something like this:

JavaScript
before(function(done) { 
ErrorMocker(/* constructor of JavaScript class goes here */);
}

Afterwards, you can use the two functions mentioned above. The next code is a sample Mocha file that shows you how to use the functions.

JavaScript
 // sample unit testing file in node.js, using mocha and later istanbul for coverage
<pre>'use strict';
var should = require('should');
var errorMocker = require("./ErrorMocker.js"); 
var HttpHelper = require("./HttpHelper.js"); // for this sample, 
                                             // I choose a class called HttpHelper
var httpHelper = new HttpHelper();
describe('Sample Mocha Unit testing file', function() {
    before(function(done) {
        errorMocker(httpHelper);
    });
    describe('Doing tests section 1', function() {
        it('Sample test on an httpHelper class that will fail a post request', function(done) {
            httpHelper.mockfailOnFunctionName("postJson", false);
            httpHelper.createPost(
              "http://rest.sampleservice.com/api/somefunction/").postJson
               (data, function (err, result) {
                // here this function call will fail with an error in the callback function,
                // effectively testing the error branch(es) inside HttpHelper
                should.exist(err);
                should.equal(err.message, "Error: mocker error");
                done();
            });
        });
    });
});  

History

  • 21st November, 2013: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
Lebanon Lebanon
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --