How do you test javascript methods visible only in the closing area?

Let's say I have the following javascript:

function Foo() { function privateStuff() { //do private stuff } this.publicStuff = function() { privateStuff(); //do other stuff } } 

It is easy enough to test publicStuff() by doing the following:

 var myFoo = new Foo(); myFoo.publicStuff(); //all the assertions 

However, I want to be able to test the privateStuff() method as my own block. I'm not sure how I could call it my own. I know using Java (with which I am much more familiar) you can use reflection to test private methods, but I'm wondering if there is a way to test these functions myself. If there is no general way to do this, I started playing with Jasmine to run my unit tests. Does this structure provide any opportunities for this?

+4
source share
2 answers

The way you have the code, you cannot. You do not allow access to privateStuff . It seems to me that you need to familiarize yourself with the concept of closure (which is fundamental to JavaScript).

Whenever you use the f() { ... } construct in JS (and several others, such as try-catch ), you always implicitly create a closure. Nesting functions, just like you, are completely legal, but if you do not give an external function an external reference to an internal function, the internal function can only be accessed from an external function.

From Mozilla :

You can insert a function inside a function. A nested (internal) function is private for its containing (external) function. It also forms a closure.

Closing is an expression (usually a function) that can have free variables along with the environment that binds these variables (which "closes" the expression).

Since a nested function is a closure, this means that a nested function can "inherit" the arguments and variables of its contents. In other words, the inner function contains the scope of the outer function.

  • An internal function can only be obtained from external function operators.
  • The inner function forms a closure: the inner function can use arguments and

Although the Mozilla documentation immortalizes this, it’s a little incorrect to say that JavaScript is private or public , because the nomenclature has a very clearly defined meaning in most programming languages ​​(such as C ++ and Java) that are polymorphic behavior or inheritance. As for JS, it’s better to think of it as a volume limit and try to get a clear idea of ​​closing.

+2
source

You cannot do this from the side, therefore it is "private". You can temporarily open it:

 this.privateStuff = privateStuff; 

Or do the testing inside the scope if possible, but you are testing it ...

+1
source

All Articles