【问题标题】:mock test if/else with Jasmine用 Jasmine 模拟测试 if/else
【发布时间】:2021-10-13 07:31:31
【问题描述】:

我有这段代码:

exportData(type: 'config' | 'equipment'): Observable<any> {
    url = '';
    if (type === 'config') url = `${path}Exportconfig`;
    else if (type === 'equipment') url = `${path}ExportEquipment`;
    
    return httpClient(...);

}

我模拟了测试,但声纳中仍然有这个消息分支应该有足够的测试覆盖率

这是我的测试

it('export configuration', () => {
    spyOn(service, 'exportData');

    const type = 'config';
    service.exportData(type)
    expect(service.exportData).toHaveBeenCalledWith('config');
})

对 type 的其他值也做了同样的事情。我想我在条件的覆盖范围内遗漏了一些东西。有什么想法吗?

【问题讨论】:

  • 那个测试没有调用任何东西。即使它确实调用了service.exportData,它也会调用spy。并且只对'config' 进行一次测试,您显然不会覆盖'equipment' 路径。目前尚不完全清楚为什么您认为这会得到充分的覆盖。
  • 对不起@jonrsharpe 我刚刚编辑了测试sn-p,我在expect之前调用了函数exportData
  • 但是你仍然在监视你应该测试的东西。当然它被调用了,你刚刚调用它 - 测试毫无意义,它只断言测试的行为
  • 你能在这里澄清更多@jonrsharpe。您实际上是在说,因为我“仅”监视该方法而不调用它,因此测试实际上并没有运行并测试所有分支?
  • 我不记得 Jasmine 间谍是否默认呼叫,但即便如此 在这里间谍活动毫无意义。并且最多覆盖一个分支,因为您只使用一个输入进行调用,您至少需要对该逻辑进行两次测试。

标签: angular typescript unit-testing sonarqube karma-jasmine


【解决方案1】:

因此显然添加了一个带有结束 *else 的最终案例,并覆盖了所有分支。 最终函数应如下所示:

exportData(type: 'config' | 'equipment'): Observable<any> {
    url = '';
    if (type === 'config') url = `${path}Exportconfig`;
    else if (type === 'equipment') url = `${path}ExportEquipment`;
    else return null;
    
    return httpClient(...);

}

【讨论】:

    【解决方案2】:

    你需要像这样修改你的测试用例:

    it('export configuration', () => {
        spyOn(service, 'exportData');
         
        // This will serve the 'if' condition
        const type = 'config';
        service.exportData(type)
        expect(service.exportData).toHaveBeenCalledWith('config');
    
    
        // This will serve the 'else-if' condition
        const type2 = 'equipment';
        service.exportData(type2)
        expect(service.exportData).toHaveBeenCalledWith('equipment');
    
        // This will serve the 'else' condition
        const type3 = 'not-equipment-not-config';
        service.exportData(type3)
        expect(service.exportData).toHaveBeenCalledWith('not-equipment-not-config');
    })
    

    【讨论】:

      猜你喜欢
      • 2021-02-16
      • 2019-12-21
      • 1970-01-01
      • 1970-01-01
      • 2013-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-19
      相关资源
      最近更新 更多