15

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

2 Answers 2

30
 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;
 }
Sign up to request clarification or add additional context in comments.

4 Comments

TypeError: this.resolve is not a function. Getting this error when tried the first approach.
how are you expecting this : private resolve; to be a function that you can call ?
nice solution.. brother
Can be done also like this expect((component as any).resolve).toEqual(false);
0

If looking to avoid eslint markings this sort of pattern also works

(component as unknown as { router: Router }).router,

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.