user13431554
user13431554

Reputation:

Angular: How to Get Private Methods into Code Coverage?

Is there anyway to add Private Methods from ng test --code-coverage into Code Coverage Reports in Angular 8?

Our Ng TestCode Coverage is low percentage, since its checking private methods.

According to articles, private methods should not require unit testing. Only the Public methods, which call private methods need to.

*Reading about tags; if any method is prefixed with public, it should be unit tested. Team can also start placing private before methods. Would this method allow ng test to find what requires testing?

https://softwareengineering.stackexchange.com/questions/100959/how-do-you-unit-test-private-methods

https://anthonysciamanna.com/2016/02/14/should-private-methods-be-tested.html#:~:text=Unit%20Tests%20Should%20Only%20Test,are%20dependent%20on%20the%20object. enter image description here

Currently testing Typescript in Angular 8.

Upvotes: 10

Views: 2449

Answers (2)

Ankit Garg
Ankit Garg

Reputation: 149

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.

Upvotes: 2

Akhil
Akhil

Reputation: 1453

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'

Upvotes: 6

Related Questions