[英]What is the best practice to test private methods in Angular 2 / Typescript
我创建了 Angular 5 项目并使用 Karma、Jasmine 编写了单元测试。 我不喜欢将所有方法公开仅用于从测试访问的想法。
export class AppComponent {
mainMenu: any[];
constructor(
private menuService: MenuService
) {}
ngOnInit(): void {
this.initTable();
this.initMenu();
}
private initTable(): void {
// ... initializes array for table
}
private initMenu(): void {
this.menuService.getMainMenu()
.subscribe(data => this.mainMenu = data);
}
}
initTable
和initMenu
方法只是用于划分代码并使代码更有条理和可读性的助手,我不需要它们在public
模式下可访问。 但在这里我面临单元测试的问题,我的测试用例应该是这样的:
it ('Should call menuService.getMainMenu', () => {
spyOn(menuService, 'getMainMenu').and.returnValue(Observable.of([]));
// this will throw exception
component.initMenu();
expect(menuService.getMainMenu).toHaveBeenCalled();
});
有任何想法吗?
您可以通过公共ngOnInit
方法实现此目的。 您可以调用ngOnInit
而不是在测试中调用initMenu
,它会间接调用私有initMenu
it ('Should call menuService.getMainMenu', () => {
spyOn(menuService, 'getMainMenu').and.returnValue(Observable.of([]));
// this will throw exception
component.ngOnInit();
expect(menuService.getMainMenu).toHaveBeenCalled();
});
私有方法是私有的是有原因的。 如果你有一个私有方法,它很复杂,你需要测试它,这是一种代码味道,表明你的代码有问题或者该方法不应该是私有的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.