Angular unit test with private variable

18,804
 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;
 }
Share:
18,804
Ish
Author by

Ish

Updated on July 29, 2022

Comments

  • Ish
    Ish almost 2 years

    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);
     });