mercredi 25 mai 2016

Best pattern for creating closures that are unit testable?

Given this:

var closure = (function() {
    var some_variable;
    var ret = {};

    function some_internal_function() {
        return some_variable;
    };

    function init() {
        some_variable = document.getElementById("canvas");
    }

    ret.some_internal_function = some_internal_function;

    return ret;
}());

I'd like to be able to some_variable to a mock object during unit testing. But this seems to be impossible. There used to be a work around with eval(), but that doesn't seem possible anymore.

I'm assuming I'll have to hijack my init() function to make the mock I want, but that seems counter to the unit testing philosophy, since I'm essentially depending on the execution of another function to dictate the behavior of the one I want to test!

I've seen some code that passes in an optional context to use during function execution and I assume that's related to testing / getting at internal variables.

I suppose I could fork a new node process, node -e closure.toString(), modify the string to var some_variable = {}; //the mock object, append a method to return the value (console.log(closure.some_internal_function())), pipe back the result to my main process and do assert()s with qunit. But that seems like trying to be a hero, when there should be a better way (if anything that seems easier than this way ><).

Is there a better way? What's the best pattern for testing this sort of thing?

Aucun commentaire:

Enregistrer un commentaire