views:

68

answers:

1

I'm writing unit tests for a module in a small Javascript application. In order to keep the interface clean, some of the implementation details are closed over by an anonymous function (the usual JS pattern for privacy). However, while testing I need to access/mock/verify the private parts.

Most of the tests I've written previously have been in Python, where there are no real private variables (members, identifiers, whatever you want to call them). One simply suggests privacy via a leading underscore for the users, and freely ignores it while testing the code. In statically typed OO languages I suppose one could make private members accessible to tests by converting them to be protected and subclassing the object to be tested. In Javascript, the latter doesn't apply, while the former seems like bad practice.

I could always fall back to black box testing and simply check the final results. It's the simplest and cleanest approach, but unfortunately not really detailed enough for my needs.

So, is there a standard way of keeping variables private while still retaining some backdoors for testing in Javascript?

+1  A: 

No. I don't believe there is. It basically boils down to whether you take the closure approach and relinquish white box tests or do white box tests and use name decoration for "private" members. Actually not only in Python, but in javascript too many projects use the not so magic underscore to decorate privates. So in a way this is already a widely accepted solution to the problem.

If you don't want that and really, really need white-box unit testing, then you can always integrate the tests into your objects. If you have a separate build step for production code (minimization, require/provide-resolution, etc) then you can remove the test functions in this process.

haffax
Well, looks like I'll have to do some decoration after all. Thanks. Incorporating the tests into the main code and removing during build is an interesting solution, but a little too messy.
Max Shawabkeh