Search code examples
javascriptunit-testingsandboxanonymous-functionqunit

Javascript Sandbox unit testing


I am using QUnit, which is excellent.

I have enclosed my JS app in the (function () {})(); sandbox. This hides a lot of code that I don't want public, but I also need to test that code.

Here is an example of how this works:

(function () {  

    var PublicAPI = window.PublicAPI = {};        
    PublicAPI.publicFunction = function (foo) {
        PrivateAPI.privateFunction(foo);
        return 'bar';
    };

    var PrivateAPI = {};
    PrivateAPI.privateFunction: function (foo) {
       // Make secret stuff that never gets returned to the public
       // Could be an AJAX call.
    }

})();

So here I can easily unit test PublicAPI.publicFunction, but how will I test PrivateAPI.privateFunction ?


Solution

  • This similar question sums it up pretty well... The easiest is to not deal with the private methods, as they can change if they want... The public methods are the ones that need testing. If you want to test your internal functions you need to leave a hook of some sort for qunit to be able to find.