Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular unit test with private variable

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);
 });
like image 504
Ish Avatar asked Oct 06 '17 08:10

Ish


People also ask

Can we test private methods in unit testing Angular?

Writing unit test for private methods and public methods is similar. But since you are unit testing an instance of an Angular component, you won't be able to access the private method.


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;
 }
like image 74
Milad Avatar answered Sep 25 '22 19:09

Milad