[英]How do I test a private method in a IIFE, maybe by using reflection?
I have some IIFEs in my javascript code structured like: 我的javascript代码结构如下:
function myIIFE() {
function mtd1() {}
function mtd2() {}
function publicmtd1() {}
return Object.freeze({
publicmtd1: publicmtd1
});
}
How can I test the private methods in this IIFE? 如何在此IIFE中测试私有方法?
I know we are not supposed to test private methods and should move them to public methods if we need to test them. 我知道我们不应该测试私有方法,如果需要测试它们,应该将它们转移到公共方法。
I am just curious if this can be done. 我只是好奇是否可以做到这一点。 In Java, I am able to test private methods by using reflection to make the methods public and then test them.
在Java中,我可以通过使用反射将这些方法公开来测试私有方法,然后对其进行测试。 I am wondering if Javascript has something similar to reflection.
我想知道Javascript是否具有类似于反射的功能。
Update: Some of you have pointed that my example code is not an IIFE. 更新:某些人指出我的示例代码不是IIFE。 You are right.
你是对的。 I should have said module instead of IIFE.
我应该说模块而不是IIFE。
IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined.
IIFE(立即调用函数表达式)是一个JavaScript函数,它在定义后立即运行。
Your example is not a IIFE , but anyways, you can't access the functions defined in the myIIFE
closure, so therefore, in this shape, you can't test them. 您的示例不是IIFE ,但是无论如何,您无法访问
myIIFE
闭包中定义的函数,因此,以这种形式,您无法对其进行测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.