【问题标题】:How do I write test cases to cover the lines within subsribe callback function如何编写测试用例来覆盖订阅回调函数中的行
【发布时间】:2020-08-31 15:03:22
【问题描述】:

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

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

【问题讨论】:

  • 因为您的订阅从未达到!你能添加更多代码,以便我可以帮助你吗
  • 谢谢,我已经为单元测试添加了代码。

标签: angular testing angular-unit-test


【解决方案1】:

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下的block了

【讨论】:

  • 天哪,非常感谢,我花了很多时间试图弄清楚这一点。我现在已经覆盖了线条。
  • 乐于助人:-),如果有帮助请采纳,谢谢。
  • 非常感谢,我已经接受了答案。 :-)
猜你喜欢
  • 2019-09-18
  • 1970-01-01
  • 1970-01-01
  • 2019-09-25
  • 2021-08-10
  • 2022-06-27
  • 1970-01-01
  • 2021-08-19
  • 2019-03-07
相关资源
最近更新 更多