在Angular 2 / Typescript

时间:2018-03-06 11:43:37

标签: angular unit-testing typescript karma-jasmine

我创建了angular 5项目并使用unit tests撰写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);
    }
}

initTableinitMenu方法只是帮助您划分代码并使其更有条理和可读,我不需要在public模式下访问它们。但在这里我遇到unit testing的问题,这是我的测试用例的样子:

it ('Should call menuService.getMainMenu', () => {
    spyOn(menuService, 'getMainMenu').and.returnValue(Observable.of([]));

    // this will throw exception
    component.initMenu();

    expect(menuService.getMainMenu).toHaveBeenCalled();
});

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您可以通过公共ngOnInit方法实现此目的。您可以调用initMenu来间接调用私有ngOnInit

,而不是在测试中调用initMenu
it ('Should call menuService.getMainMenu', () => {
    spyOn(menuService, 'getMainMenu').and.returnValue(Observable.of([]));

    // this will throw exception
    component.ngOnInit();

    expect(menuService.getMainMenu).toHaveBeenCalled();
});

出于某种原因,私人方法是私有的。如果你有一个复杂的私有方法,你需要对它进行测试,那就是代码味道,表明你的代码有问题,或者方法不应该是私有的

相关问题