Using Sinon+Rewire for Unit Testing with Private Methods

How many times have you tried to follow good programming practices by creating well-defined, single-purposed methods and only exposing the necessary public methods outside of your library and become frustrated with attempting to write unit tests for your code? You then begin to question your decisions about which method(s) should be public and which methods should be private. Additionally, you start to wonder if 100% code coverage is truly necessary. I mean, 75% of code coverage isn’t really that bad, is it? It’s better than 10%, right?

If you scour the web for suggestions, there’s a number of less-than-optimal solutions for this problem. First, I’d like to cover some of these solutions and why they are less than ideal. Second, I’ll provide some production code that contains a private method along with how to successfully achieve 100% coverage with unit tests. The examples provided are in Node.js.

Read more