Getting Started

Testing an existing piece of software holds a different set of challenges from testing something you are writing, particularly if it is of any size. The Timepicker Addon had just over 2100 lines of code when I started.

You first need to choose where to start. Testable entities—functions in JavaScript—that have few or no dependencies, provide you a way to start with something simpler—a way to get a foothold—and work your way up the chain. The first commit, of course, was just setting up the test framework [72007f6].

I chose to start with a series of top-level private functions within the immediately invoked function expression (IIFE) that wraps every well-written jQuery plugin. But the functions were private, so I had to decide how to expose them for testing. In JavaScript, things are generally either hidden or not, rarely in between. However, some programmers use naming conventions to designate exposed functions as private. Trent used an underscore to mark some functions as private. I followed his lead. Listing 15-1 shows the relevant subset of the IIFE and the technique I used to access the functions.

Listing 15-1: Exposing private functions in an IIFE for testability

(function($) {
  var extendRemove = function(target, props) { ... };
  var isEmptyObject = function(obj) { ... };
  var convert24to12 = function(hour) { ... };
  var detectSupport = function(timeFormat) { ... };

  $.timepicker._util = {
    _extendRemove: extendRemove,
    _isEmptyObject: isEmptyObject,
    _convert24to12: convert24to12,
    _detectSupport: detectSupport
  };
})(jQuery);

Exposing these internal methods by making them underscore-prefixed methods of an underscore-prefixed object on the timepicker let me access them from tests like

$.timepicker._util._extendRemove(target, props);

for very easy testing. The initial 19 tests, through commit [d0245b6], fixed two bugs and enabled safe, test-protected simplification of other code.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.146.176.88