How to expose private functions for unit testing

Javascript scope mechanics don’t allow you to access the private functions of a class/function which makes it pretty hard to unit test.
Your alternatives usually are either to create a unit test function inside your code to expose your other private functions or change your code style to expose all functions all the time (please let me know if there are more options.

I’ve come up with one more solution. By injecting code into the class string, we can create a method that returns all private functions and exposes them for what ever unit test needs you might have. The code creates an instance of the class and doesn’t modify your original code.

Lets pretend you have this overcomplicated function/class:

var Foo = function() {functionadd(a,b) {return a + b;
}
}

When we create an instance of it: var boo = new MyClass(); we can’t access boo.add because it’s private so we cant test it.

But if with a little help of a small function I wrote, we create an instance like this:

var fooExposed = getExposedInstance(Foo);

We get an instance of boo with a property called _privates that exposes all internal functions. In this case, we can access add() like this: