I've created Angular 5 project and writing unit tests using Karma, Jasmine. I don't like the idea of making all methods public only for accessing from tests.
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
and initMenu
methods are just helpers for dividing the code and make more organized and readable, I don't need them to be accessible in public
mode. But here I'm facing the problem with unit testing, here's how my test case should look like:
it ('Should call menuService.getMainMenu', () => {
spyOn(menuService, 'getMainMenu').and.returnValue(Observable.of([]));
// this will throw exception
component.initMenu();
expect(menuService.getMainMenu).toHaveBeenCalled();
});
Any ideas?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…