How do I test a private method with Jasmine Unit t

2020-03-30 04:09发布

问题:

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

回答1:

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)