tymspy tymspy - 5 months ago 193
AngularJS Question

How to write unit testing for Angular 2 / TypeScript for private methods with Jasmine

How do you test a private function in angular 2 ?

class FooBar {

private _status: number;

constructor( private foo : Bar ) {
this.initFooBar();

}

private initFooBar(){
this.foo.bar( "data" );
this._status = this.fooo.foo();
}

public get status(){
return this._status;
}

}


The solution I found


  1. Put the test code itself inside the closure or Add code inside the closure that stores references to the local variables on existing objects in the outer scope.

    Later strip out the test code using a tool.
    http://philipwalton.com/articles/how-to-unit-test-private-functions-in-javascript/



Please suggest me a better way to solve this problem if you have done any?

P.S


  1. Most of the answer for similar type of question like this one doesn't give a solution to problem, that's why I'm asking this question

  2. Most of the developer say you Don’t test private functions but I don't say they are wrong or right, but there are necessities for my case to test private.


Answer

As most of the developers don't recommend testing private function, I agree to that partially, not all private functions should be tested. There might be some cases where the private functions are touch points of another API but you should decide whether to test it or not.

Eg.

YourClass.ts

export class FooBar {
  private _status: number;

  constructor( private foo : Bar ) {
    this.initFooBar({});
  }

  private initFooBar(data){
    this.foo.bar( data );
    this._status = this.foo.foo();
  }
}

TestYourClass.spec.ts

describe("Testing foo bar for status being set", function() {

...

//Variable with type any
var fooBar;

fooBar = new FooBar();

...
//Now this will be visible
fooBar.initFooBar();

...
}

Thanks to @Aaron, @Thierry Templier.