In typescript, what is the best way to test a private method. While testing a controller in Angularjs, sometimes controller add a property (function) to $scope, and if I do not make the property public, then assign to the $scope, I may to be able to test it. Is there a recommended way.
export class MyCtrl{
constructor($scope){
$scope.addProp = (d:string) => {
this.addProp();
}
}
private addProp(){
//...
}
}
Unit Tests Should Only Test Public Methods The short answer is that you shouldn't test private methods directly, but only their effects on the public methods that call them. Unit tests are clients of the object under test, much like the other classes in the code that are dependent on the object.
So whether you are using JUnit or SuiteRunner, you have the same four basic approaches to testing private methods: Don't test private methods. Give the methods package access. Use a nested test class.
Use the TestVisible annotation to allow test methods to access private or protected members of another class outside the test class. These members include methods, member variables, and inner classes. This annotation enables a more permissive access level for running tests only.
One solution is to rearchitect your code so that it is more testable. You could create an AddPropProvider
that does the actual work (with implementation details more exposed for testing) and pass it in to the constructor for MyCtrl
. That's the classic inversion of control strategy.
Another solution is maybe just make that function public after all? Private is ideal for hiding implementation details that could change, but maybe you know that function is always going to be there anyways.
Finally there's the hack. That function really exists on the instances of MyCtrl
and the compiler only doesn't want you calling it because you said so.
var m = new MyCtrl();
(<any>m).addProp();
Now if you remove or modify the signature for addProp
that code will still compile so you've lost type safety. In most code that would be bad. But this is unit test code so we're going to learn about the break early and easily so it's not horrible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With