Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
191 views
in Technique[技术] by (71.8m points)

unit testing - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...