What is the best practice to test private methods in Angular 2 / Typescript

空扰寡人 提交于 2019-12-14 03:24:00

问题


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?


回答1:


You could achieve this via the public ngOnInit method. Instead of calling initMenu in your test, you can call ngOnInit which indirectly calls the private initMenu

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

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

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

Private methods are private for a reason. If you have a private method, which is complicated and you need to test it, it is a code smell, indicating a problem with your code or the method should not be private



来源:https://stackoverflow.com/questions/49130030/what-is-the-best-practice-to-test-private-methods-in-angular-2-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!