You are viewing our old blog site. For latest posts, please visit us at the new space. Follow our publication there to stay updated with tech articles, tutorials, events & more.

Q-Unit : Test your private code

0.00 avg. rating (0% score) - 0 votes
A tested and well-documented code is what we all strive for.
At naukri.com Q-Unit (JavaScript testing framework) has been the integral part of the Front End Development (FED) team since last one year.
Qunit is cool but when it comes “Testing JavaScript’s private functions without modifying the code”  it gets rigid.
Let us see step-by-step how we solved the above problem:
  1. Design plugins in object literal format
In object literal format every function is global. Though it makes testing easy but it exposes all our functions which is a paltry way of coding.
Example.
API  = {
private : function(){},  //no more private
public : function(){}
}
  1. Keeping separate copy for testing
For better API design we used modular pattern but it is all private with selective public methods. To test various private module we maintained two version of the same file:
  • Development version
  • Testing version
Required private functions are made public in the testing version. But this time keeping two files in synch was a major challenge.

Development version
Testing Version
API = (function(){
var private = function(){}
var public = function(){}
return {public:public}
}())
API = (function(){
var private = function(){}
var public = function(){}
return {public:public,
private:private}
}())

Solution to the problem
A global testObject is defined in the actual testing environment.  Every private function is defined as a property of this global testObject.  If the testObject is available to the code it is used otherwise a new local object is made to hold all the functions.

Normal environment
Testing Environment

API = (function(){
            var t = typeof testObject !=   “undefined” ?testObject : {};
var private = function(){}
var public = function(){}
return {public:public}
}());
var testObject = {};
API = (function(){
           var t = typeof testObject != “undefined” ?testObject : {};
t.private = function(){}
t.public = function(){}
return {public:public,
private:private}
}());

Posted in General