Say I have the following javascript:
function Foo() {
function privateStuff() {
//do private stuff
}
this.publicStuff = function() {
privateStuff();
//do other stuff
}
}
It’s 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 its own unit. I’m not sure how I could go about calling it on it’s own. I know with Java (with which I am much more familiar) you can use reflection to test private methods, but I’m wondering if there’s any way to test these functions on their own. If there’s no general way of doing this, I’ve started playing around with Jasmine to run my unit tests. Does this framework provide any capability for this?
The way you have your code up there, you can’t. You don’t allow anything to have scoped access to
privateStuff. It seems to me that you need to read up on the concept of closures (which is fundamental to JavaScript).Whenever you use a
f() { ... }construct in JS (and several others, liketry-catchblocks), you always implicitly create a closure. Nesting functions as you did is perfectly legal, but unless you give the external function an external reference to the internal function, the internal function can only be accessed from within the external function.From Mozilla:
Even though the Mozilla documentation perpetuates this, it’s slightly incorrect to say stuff is
privateorpublicin Javascript as the nomenclature has very well-defined meaning in most programming languages (like C++ and Java) that relates to polymorphic behavior or inheritance. As far as JS is concerned, it’s better to think of it as scope-limited and try to gain a strong understanding of closures.