samedi 17 juin 2017

How To Unit JS Test Enclosures

I have a bunch of code placed within an enclosure $(document).ready(). I want to re-factor it so I can unit test it as an observer cannot access funcA(), funcB(), and funcC(). I am wondering how I should approach this. My idea was to pull out the contents into its own object, and call init() from within the $(document).ready(). Is there a cleaner or ideal approach to this?

// Original
$(document).ready( function() {
    $('.my-class').on('click', function() {
        funcA();
        funcC();
    });

    $('.my-class').on('hover', function() {
        funcA();
    });

    function funcA() {}
    function funcB() {}
    function funcC() {
        funcB();
    }
});


// Modified
$(document).ready( function() {
    app.init();
});
var app = window.app || (function() {
    function init() {
        $('.my-class').on('click', function() {
            funcA();
            funcC();
        });

        $('.my-class').on('hover', function() {
            funcA();
        });
    }

    function funcA() {}
    function funcB() {}
    function funcC() {
        funcB();
    }

    return {
        init: init,
        funcA: funcA,
        funcB: funcB,
        funcC: funcC
    }
})();

Aucun commentaire:

Enregistrer un commentaire