【问题标题】:What is the best practice to test private methods in Angular 2 / Typescript在 Angular 2 / Typescript 中测试私有方法的最佳实践是什么
【发布时间】:2018-03-06 11:43:36
【问题描述】:

我创建了 Angular 5 项目并使用 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 模式下访问它们。但是在这里我遇到了单元测试的问题,我的测试用例应该是这样的:

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

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

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

有什么想法吗?

【问题讨论】:

标签: angular unit-testing typescript karma-jasmine


【解决方案1】:

您可以通过公开的ngOnInit 方法实现此目的。您可以调用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();
});

私有方法是私有的是有原因的。如果你有一个私有方法,它很复杂,你需要测试它,这是代码异味,说明你的代码有问题或者方法不应该是私有的

【讨论】:

  • code-coverage的观点来看,这不是解决方案,在这种情况下code-coverage不会覆盖initTableinitMenu方法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-16
  • 1970-01-01
  • 2022-01-01
  • 2010-09-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多