简体   繁体   English

Javascript Sandbox单元测试

[英]Javascript Sandbox unit testing

I am using QUnit, which is excellent. 我正在使用QUnit,这非常棒。

I have enclosed my JS app in the (function () {})(); 我把我的JS应用程序包含在(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 ? 所以在这里我可以轻松地对PublicAPI.publicFunction单元测试,但是我如何测试PrivateAPI.privateFunction

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. 如果你想测试你的内部函数,你需要留下某种钩子以便qunit能够找到。

You can't. 你不能。 There is no way to access it from outside of that scope. 无法从该范围之外访问它。 Your only hope is to integration test it, ie 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? 有什么大不了的?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM