首页 > 解决方案 > 如何编写测试用例来覆盖订阅回调函数中的行

问题描述

在我的组件中,我有以下代码:

setTakenNcatsNames(): void {
    if (this.settings.route){

    this.dataService.getAll(this.settings.route).subscribe(result => 
    {
            console.log('in herer');
            this.arrTakenNcatsNames = result
        });
    }
}

如何编写测试用例来覆盖 .subscribe() 回调中的行?无论我尝试什么,我在 .subscribe 中的行总是显示为未覆盖。[2]

我的报道总是告诉我这个:

`

setTakenNcatsNames(): void {
        Eif (this.settings.route){
            this.dataService.getAll(this.settings.route).subscribe(result => {
                **console.log('in herer');**
                **this.arrTakenNcatsNames = result**
            });
        }
    }

`

这是我的测试用例,我在这里缺少什么?

describe('setTakenNcatsNames()', () => {
    fit('sets the array for taken NCATS names', fakeAsync(() => {
        component.setTakenNcatsNames();
    }));
});

标签: angulartestingangular-unit-test

解决方案


添加间谍dataService.getAll

fit('sets the array for taken NCATS names', fakeAsync(() => {
    const service: DataService = TestBed.get(DataService);
    spyOn(service, "getAll").and.returnValue(of('test');// create a mock result instead of test
    component.setTakenNcatsNames();
    expect(component.arrTakenNcatsNames ).toBe('test');// or mock result 
    }));

这样你就可以在 subscribe 下测试区块


推荐阅读