Angular: How to Get Private Methods into Code Coverage?

I am adding few more points to the answer explained above by Akhil.

  1. I see ternary operations used in your code. Make sure you are writing test cases to cover all scenarios. (Negative, Positive or based on some specific value). Same goes for all conditional things you are going to do in your code.

  2. Once you run your test cases make sure you are opening developer tools and debug the actual process. This is because sometimes your code will give exception but still your test case will pass. In this case most of the lines after exceptions will not be covered.

Always make sure there is no console error in your test case run also. Chrome debugger tool should be on priority.

Hope this will help you.

Code coverage checks for private methods too.

Generally, there are 2 scenarios where private method gets called.

  • If private method gets called inside a public method (directly or if satisfies any condition)

For this case, you will need to call the public method in your tests and cover the underlying private method directly and satisfying the condition from your tests.

  • If the private method gets called from a DOM event say button click

For this case, you will need to capture the button using By.css and fire click event.

Note :: Till Angular ivy got introduced, we could bind button click event to private method in TS class but from now on its not possible. It will give compilation error.

Property 'onClickMethod' is private and only accessible within class 'AppComponent'