How do I test a private method with Jasmine Unit tests

ⅰ亾dé卋堺 提交于 2019-12-09 03:26:31

问题


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)



来源:https://stackoverflow.com/questions/48093434/how-do-i-test-a-private-method-with-jasmine-unit-tests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!