trevmex's tumblings

JavaScripter, Rubyist, Functional Programmer, Agile Practitioner.

A JavaScript template for making testable private functions

Ever want to have a class in JavaScript that has private functions that are complex enough that you want to test them? You could split the private functions out into their own class, but let’s say you don’t want to do that. This is a creative way to make testable private functions.

Basically, we create a class with three internal objects:

  • private: this holds all our private functions. This means that any private function call will start with private.
  • public: this holds all the public functions. You shouldn’t be calling public functions directly, but if you must, you have to call them with public.
  • settings: this holds the debug option. If debug is true, we will merge the private and public functions together for testing purposes.

Creating an instance of the class without options will create it normally with private functions as truly private.

When you are writing your unit tests, you instantiate the class with {debug: true} and the public and private functions will all be available for public testing. Tada!

if (typeof NS === 'undefined' || !NS) {
    var NS = {};
}

(function ($) {
    NS.Klass = function(options) {
        var settings = {
                debug: false
            },
            private = {
                // Private Functions
            },
            public = {
                // Public Functions
            };

        if (options) {
            $.extend(settings, options);
        }

        if (settings.debug) {
            return $.extend({}, private, public);
        } else {
            return public;
        }
    };
}(jQuery));

var myClass = new NS.Klass(); // Regular usage

var myDebugClass = new NS.Klass({debug: true}); // Debug usage

Note: This implementation uses jQuery’s $.extend() function. There might be a better way of doing this without jQuery. I am open to other implementations. Feel free to fork it and show me the way!

Notes

  1. trevmex posted this