- Thinking About Static vs. Private Methods In TypeScript / Angular 2
- Correct Answer
- Unit Testing with TypeScript – 3 Tricks to help you with private method
- Subscribe to RSS
- How to unit test private method in TypeScript (part 2)
Unit Testing with TypeScript – 3 Tricks to help you with private method
I already posted about how to write unit tests for private method with TypeScript about one year ago. Few days ago, I had the same discussion that I had in my previous team concerning private method. The situation is similar. At first, it may sound that we are going inside those private methods, therefore we are doing proper unit testing. The problem by going through intermediate methods to access the one we want to test is that any change on intermediate methods will make multiple test to fail. When a unit tests fail, the goal is to know which unit of your code is failing. Imagine the situation where you have class A that has method a1a2a3. You want to to unit test a3but the only entry point is a1 which is the only method public. This one call a2who call in some particular situation a3. You have multiple conditions in a3 and you evaluate that you need 5 unit tests. The problem is that if a1 or a2 change in the future that all these 5 tests may fail, when they should not. At that point, most people understand the situation and agree to test the private methods. However, there is some good ways to do it and some bad ways. The worst way to do it to cast the class A to be of type any and call a3 directly. Something like :. The problem with the above code is that when you will refactor a3 to have a better name that no tool will find out this instance. More, this open the door to access private fields or inject new functions and fields to the class. At the end, it become a nightmare to maintain. We are using TypeScript to be strongly typed, our tests should continue to be as strong. In the previous article I wrote, I talked about 2 patterns. The first one is about working around encapsulation with an interface.
Subscribe to RSS