tymspy tymspy - 1 year ago 611
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 ) {


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.

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


  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 Source

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.



export class FooBar {
  private _status: number;

  constructor( private foo : Bar ) {

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


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


//Variable with type any
var fooBar;

fooBar = new FooBar();

//Now this will be visible


Thanks to @Aaron, @Thierry Templier.