Angular unit test with private variable

Viewed 22117

I want to write the unit test for the private variable. But Jasmine is not allowing me to use it. Can someone explain me how to do it?

export class TestComponent implements OnInit {
  private resolve;

  public testPrivate() {
    this.resolve(false);
  }
}

 it(
      'should test private variable', () => {
        component.testPrivate();
        expect(component.resolve).toEqual(false);
 });
1 Answers
 expect(component['resolve']).toEqual(false);

or

 expect((<any>component).resolve).toEqual(false);
enter code here

However, technically you should not be testing a Private variable simply because it's private member of a class and it's meant to be accessed only within the class itself, if you really wanna test it, you have to make it public or create a getter setter for it which are public.

And by the way, your test doesn't make much sense to me, unless you haven't written the whole test in here.

Cause you're calling this.resolve(false), meaning that it's a function , then why are you testing it to be equal to false ?

EDIT :

did you mean this : ?

 public testPrivate() {
   this.resolve = false;
 }
Related