【问题标题】:Unit testing function ehich return observable of observables返回可观察对象的单元测试功能
【发布时间】:2022-01-24 23:01:09
【问题描述】:

我遇到了这样的单元测试功能问题:

loadData({prop1, prop2, prop3}: Props): Observable<unknown> {
    return this.dataService.clearData().pipe(
         concanMap(() => this.personalDataService.getData(prop1)),
         concanMap(() => this.extendedDataService.getData(prop2)),
         concanMap(() => this.weatherDataService.getData(prop3))
    );
}

我想根据 spyOn 来做这件事。像这样的:

it('should correctly load data', () => {
    spyOn(dataService, 'clearData');
    spyOn(personalDataService, 'getData');
    spyOn(extendedDataService, 'getData');
    spyOn(weatherDataService, 'getData');

    spectator.service.loadData({
          prop1: '',
          prop2: '',
          prop3: ''
    })

    expect(dataService.clearData).toHaveBeenCalled();
    expect(personalDataService.getData).toHaveBeenCalled();
    expect(extendedDataService.getData).toHaveBeenCalled();
    expect(weatherDataService.getData).toHaveBeenCalled();
});

我有一个错误:

TypeError: Cannot read properties of undefined (reading 'pipe')

很明显,因为dataService.clearData是一个mock,所以我需要从这个方法中返回一些值:

spyOn(dataService, 'clearData').and.returnValue(of());

此解决方案不好,因为无法触发其他服务调用。

你知道如何测试这个功能吗?

【问题讨论】:

  • 测试替身需要与他们所代表的东西具有相同的界面。在这种情况下,这意味着它们(全部!)需要返回可观察对象,而不是未定义的。
  • 你是对的,但所有 getData() 函数只有在我模拟它们以响应 clearData() 时才会被调用。我想避免它。

标签: angular unit-testing jestjs angular-spectator


【解决方案1】:

我认为您的测试应该检查 loadData 是否按预期返回,如下所示:

// mock clearData() and the three getData() here

testedComponent.loadData(...).subscribe((actual) => {
    // assert that actual is as expected
})

在您的测试中,您只需调用 spectator.service.loadData(),这会给您留下一个冷的 observable。

【讨论】:

    猜你喜欢
    • 2020-07-29
    • 2018-04-11
    • 2017-07-12
    • 2018-04-28
    • 2018-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-13
    相关资源
    最近更新 更多