3

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'."

3
  • 2
    make a public wrapper for test purposes?
    – Ronald
    Commented Jan 4, 2018 at 10:40
  • Seems like its by design
    – AngularM
    Commented Jan 4, 2018 at 10:42
  • Why do you want to test a private method? Testing implementation details is not a good idea, isn't it? I think that you should test only public methods because it's api of your component. Commented Jan 5, 2018 at 19:20

1 Answer 1

3

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)

2
  • Im using typescript
    – AngularM
    Commented Jan 4, 2018 at 10:45
  • 2
    Just because Typescript is compiled to Javascript we should not use private functions? Then we can abandon the whole Typescript concept anyway. Commented Aug 27, 2018 at 1:00

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.