简体   繁体   中英

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM