AngularM
AngularM

Reputation: 16618

How do I test a private method with Jasmine Unit tests

I want to call a private method in my component

Private Method:

  private test(): void {
     return true;
  }

Spec It:

  it('should call test method and return true', () => {
     const response = component.test();
     expect(response).toBeTruthy();
  });

Issue:

Says: "Property 'test' is private and only accessible within class 'MyTestComponent'."

Upvotes: 3

Views: 5625

Answers (1)

user4676340
user4676340

Reputation:

You could use

component['test']();
// OR in your component, add
callMethod() {
  this.test();
}

But if I were you, I would remove the private attribute. In Javascript, there's no private attributes, only scopes.

If you want to test your method and you can't, it means you should change your code, not adapt your test to your code. That's how you get simple and efficient code.

(But again; that was just my two cents on your matter)

Upvotes: 3

Related Questions