[英]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.