我如何测试IIFE的“私人”方法?

时间:2022-01-02 22:56:44

Supose that i have this:

说我有这个:

var myObj = (function() {
    function private1() {
        console.log("private");
    }

    return {
        public1: function() {
            private1();
            console.log("public");
        }
    }
})();

How could i test the "private1" function?

我怎么能测试“private1”功能?

1 个解决方案

#1


4  

Check this out How to test private functions in javascript. Summarizing the post, you could achieve what you want by improving your build process. If you use grunt to build your code then you could add some pieces of code that exposes the private elements of your IIFE only at testing time.

看看这个如何在javascript中测试私有函数。总结这篇文章,您可以通过改进构建过程来实现您想要的目标。如果您使用grunt构建代码,那么您可以添加一些代码片段,这些代码片段仅在测试时公开IIFE的私有元素。

Also you may want to try this build tool selectizer. With it you could define your private1 function as a module and then testing it by just loading the function with requireJS.

您也可以尝试使用此构建工具选择器。有了它,您可以将private1函数定义为模块,然后通过仅使用requireJS加载函数来测试它。

#1


4  

Check this out How to test private functions in javascript. Summarizing the post, you could achieve what you want by improving your build process. If you use grunt to build your code then you could add some pieces of code that exposes the private elements of your IIFE only at testing time.

看看这个如何在javascript中测试私有函数。总结这篇文章,您可以通过改进构建过程来实现您想要的目标。如果您使用grunt构建代码,那么您可以添加一些代码片段,这些代码片段仅在测试时公开IIFE的私有元素。

Also you may want to try this build tool selectizer. With it you could define your private1 function as a module and then testing it by just loading the function with requireJS.

您也可以尝试使用此构建工具选择器。有了它,您可以将private1函数定义为模块,然后通过仅使用requireJS加载函数来测试它。