Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there anyway to unit test javascript functions defined within a function?

I would just like to ask whether I would be able to unit test the code inside ExternalFunction within the document.ready? I have tried many things for a while now and still couldn't work out how, and am at my wits end.

$(document).ready(function () {
    var originalExternalFunction = ExternalFunction;
    ExternalFunction = function(context, param) {
        // trying to unit test the stuff in here!
    }
}

I'm unit testing using JsTestDriver. Test declaration is something like TestThisTest.prototype.test_this - function() {};

Thanks in advance.

like image 208
BeraCim Avatar asked Dec 10 '25 22:12

BeraCim


2 Answers

Since, in your example, ExternalFunction is not declared within the scope of the function, it is global (or at least, in whatever scope it may have been defined in outside ready). You can therefore test it by calling it as a global.

The trouble is, in order to assign the function to ExternalFunction, you have to run ready (which you could run manually, if you need). This means that if you put any other functionality in ready, then no, it is not unit testable. If your example code is an accurate reflection of reality, then I suppose it is kinda testable.

The point of a construct like this, is to hide the inner function. If you don't wish to hide it, then Anon.'s suggestion of defining newExternalFunction in a more accessible scope is what you need.

If your function needs to be a closure using variables from within ready, you could define newExternalFunction thus:

   var newExternalFunction;
    $(document).ready(function () {
        var originalExternalFunction = ExternalFunction;
        newExternalFunction = function(context, param) {
            // trying to unit test the stuff in here!
        }
        ExternalFunction = newExternalFunction;
    }

You would still need to ensure that ready has run, prior to unit testing, but you wouldn't have to rely on ExternalFunction not being reset to originalExternalFunction.

like image 118
Paul Butcher Avatar answered Dec 12 '25 11:12

Paul Butcher


You could do something like:

function newExternalFunction(context, param) {
    //etc.
}

$(document).ready(function () {
    var originalExternalFunction = ExternalFunction;
    ExternalFunction = newExternalFunction;
}

Then it's relatively straightforward to run your unit tests on newExternalFunction.

like image 29
Anon. Avatar answered Dec 12 '25 13:12

Anon.