Javascript Sandbox unit testing

穿精又带淫゛_ 提交于 2019-12-13 13:08:16

问题


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 ?


回答1:


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.




回答2:


You can't. There is no way to access it from outside of that scope. Your only hope is to integration test it, i.e. test functions on the globally available object that are using your internal functions.

Better yet: don't make private functions. What's the big deal?



来源:https://stackoverflow.com/questions/2230469/javascript-sandbox-unit-testing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!