Pregunta

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(){
        //...
    }
}
¿Fue útil?

Solución

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.

Otros consejos

One solution is to not use the scope as the strong glue to ui and only use it as a container for the controller class instance.this also has other advantages http://www.youtube.com/watch?v=WdtVn_8K17E

Then you can simply test your controller as you would test any other JavaScript class and not worry and $scope in your tests.

While I agree with Jeffery Grajkowski's solutions proposed above, there is one more option you should consider. Since JavaScript (and, by extension, TypeScript) doesn't have "real" private types, make it public, but private by convention.

That is, have the method name start with an underscore or "unitTest", so anyone who sees it will recognize that it shouldn't be used in production code.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top