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

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

本文介绍了在Angular 2/Typescript中测试私有方法的最佳实践是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了Angular 5项目,并使用Jasmine的Karma编写了单元测试.我不喜欢公开所有方法仅用于从测试访问的想法.

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);
    }
}

initTableinitMenu方法只是划分代码并使它们更具组织性和可读性的帮助者,我不需要它们可以在public模式下访问.但是在这里,我面临着单元测试的问题,这就是我的测试用例的外观:

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();
});

有什么想法吗?

推荐答案

您可以通过公共ngOnInit方法来实现.您可以调用ngOnInit间接调用私有initMenu

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

这篇关于在Angular 2/Typescript中测试私有方法的最佳实践是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 03:00