简体   繁体   English

在 Angular 2/Typescript 中测试私有方法的最佳实践是什么

[英]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.我创建了 Angular 5 项目并使用 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. initTableinitMenu方法只是用于划分代码并使代码更有条理和可读性的助手,我不需要它们在public模式下可访问。 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.您可以通过公共ngOnInit方法实现此目的。 Instead of calling initMenu in your test, you can call ngOnInit which indirectly calls the private initMenu您可以调用ngOnInit而不是在测试中调用initMenu ,它会间接调用私有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如果你有一个私有方法,它很复杂,你需要测试它,这是一种代码味道,表明你的代码有问题或者该方法不应该是私有的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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