我想在我的组件中调用一个私有方法
私人方法:
private test(): void {
return true;
}
规格:
it('should call test method and return true', () => {
const response = component.test();
expect(response).toBeTruthy();
});
问题:
说:“属性'测试'是私有的,只能在'MyTestComponent'类中访问。”
你可以用
component['test']();
// OR in your component, add
callMethod() {
this.test();
}
但如果我是你,我会删除私有属性。在Javascript中,没有私有属性,只有范围。
如果你想测试你的方法而你不能,那就意味着你应该改变你的代码,而不是让你的测试适应你的代码。这就是你如何获得简单而有效的代码。
(但又一次;这只是我对你问题的两分钱)