Notes On Writing Testable JavaScript Vol 1

When writing JavaScript, I am a big fan of minimizing functionality and variables exposed publicly, which we all know to be good practice. However, this leads to anonymous functions and functions hidden within closures.  So….

How Do You Test That?

How exactly do you test private methods in JavaScript?  To answer that you should ask yourself, should I even be testing them independently or can I write tests for the exposed functionality and still achieve code coverage?  If the answer to that question is “yes,” write tests for the exposed functionality that inherently test the underlying private functions and stop there.  If the answer is “no, I really need to test this function.”  There are a few approaches.

Member Variables For Testing Only

This approach involves creating member variables intended for testing and testing alone.  This method relies on the build process to remove the variables before going to production.  While this process works, I believe it has a code smell to it.  You are polluting and bloating the code base with needless variables.  If you are interested in the approach, here is an article about it.

The Real Question: Should It Be There?

Is the fact that you are asking this question an indicator of a code design issue?  Perhaps the code is in violation of the Single Responsibility Principle?  I’ve recently experienced a little epiphany associated with this.  I realized that a collection of private functions that I was hiding actually belonged to a separate object as public functions.  This refactoring drastically reduced the code complexity, made it more maintainable, and enabled small, important functions to be separately tested.
 
 
 
 
 

1 Comment

Leave a Reply