【问题标题】:Returning 2 different values using using a mock service while unit testing in Angular在 Angular 中进行单元测试时使用模拟服务返回 2 个不同的值
【发布时间】:2020-08-26 09:38:55
【问题描述】:

问题总结:

如何在同一个测试规范中使用同一个服务调用多个值并检查它是否与组件中的完全一样?

我正在使用 Angular7+。

假设有一个组件(比如 A ),其中注入了服务。

假设,在同一个 service 中有一个 getNumber 函数,它有 2 个参数,即 ( "Key" , "Value" ) 其中 " Key”只能是num1num2,而“Value”可以是任何整数

此函数以这种格式返回一个对象:{ "Key" : num1 or num2 , "Value" : number } 并且该对象存储在另一个对象中(比如 Total ) 作为它的元素。示例:

export class A implements OnInit{
 Total={"sum":["num1","num2"],"amount":0};

 constructor(private service: SomeService) {}
    ngOnInit(){
        this.loadFunc();
    }

    private loadFunc(){
        this.service.getNumber("num1",12).subscribe(res =>{
                Total[res.Key] = res.Value;
        },err=>{
            console.log(err);
        });

        this.service.getNumber("num2",13).subscribe(res =>{
                Total[res.Key] = res.Value;
        },err=>{
            console.log(err);
        });

        this.calculate();
    }

    private calculate(){
        //For elements in Total.sum array iterate over them and store the value in any other key say amount.
        for(const keys of Total["sum"]){
            if(Total[keys]){
                Total["amount"] += Total[keys];
            }
        }
        console.log(Total["amount"]);      // Outputs to 25
    }
}

So Total would become : 
Total = { "num1":12 , "num2":13 ,"sum":["num1","num2"],"amount":25};

现在在 单元测试 服务组件中,我有一个带有 getNumber 函数的 mockService 存根,我正在做这样的事情:

mockServiceStub = jasmine.createSpyObj(['getNumber']); // done before testbed.createComponent()

// Inside Test
mockServiceStub.getNumber.and.returnValue(of({"Key":"num1", "Value":12}));
fixture.ngOnInit();
console.log(component.Total.amount); // outputs 12

mockServiceStub.getNumber.and.returnValue(of({"Key":"num2", "Value":13}));
fixture.ngOnInit();
console.log(component.Total.amount); // outputs 13
expect(component.Total.sum).toEqual(25); // throws error 'Expected 13 to equal 25'

我实际上希望将这两个值结合起来,即在我的测试中, 我首先以“num1”为键返回值 12,然后以“num2”为键返回 13,我预计输出为 25(12 + 13)。

【问题讨论】:

  • 嗯,我从来没有看到你在你的测试脚本上调用计算。我觉得我需要查看更多您的测试代码和组件的实际实现。究竟是什么答案?如何将服务作为存根注入到组件中?
  • 我不需要像在执行 fixture.detectChanges() 时那样调用计算 ngOnInit 被调用并在其中计算。答案应该是(根据我),因为我第一次调用的值为 12,第二次调用的值为 13,所以第二次调用计算总和应该是 25。但是它只显示 12。
  • mockServiceStub.getNumber.and.returnValues(of({"Key":"num1", "Value":12}),of({"Key":"num1", "Value": 13}));试试这个
  • 没有人,不工作。
  • 我很抱歉造成混乱。请检查我对问题的最新编辑.. 我试图解释和改变它一点。

标签: angular unit-testing observable


【解决方案1】:

这有效.. returnValues 有 2 个不同的值:

mockServiceStub.getNumber.and.returnValues(of({"Key":"num1", "Value":12}, {"Key":"num2", "Value":13}));
fixture.detectChanges();     
expect(component.Total.sum).toEqual(25);

【讨论】:

    【解决方案2】:

    试试这个代码。

    mockServiceStub.getNumber.and.returnValues( of ({
      "Key": "num1",
      "Value": 12
    },{
      "Key": "num2",
      "Value": 13
    }));
    fixture.detectChanges();
    expect(component.Total.sum).toEqual(25);
    
    //update
    
    async ngOnInit() {
      await this.loadFunc();
    }
    
    private async loadFunc() {
      await this.service.getNumber("num1", 12).subscribe(res => {
        Total[res.Key] = res.Value;
      }, err => {
        console.log(err);
      });
    
      await this.service.getNumber("num2", 13).subscribe(res => {
        Total[res.Key] = res.Value;
      }, err => {
        console.log(err);
      });
    
      this.calculate();
    }

    【讨论】:

    • 对不起,这在我的系统上不起作用。你试穿了吗?
    • 只取第一个值(这里是12)..不知道为什么...
    • 我没有尝试过,但似乎 ngOnInit 方法存在问题,因为您使用的是异步(订阅者),然后同步分配 Total。我怀疑你的代码是否真的有效。
    • 实际程序有效.. 测试无效。假设一切都是同步的,那么测试部分是否也可以工作?
    • 还有什么建议?比如我应该如何改变我的程序?
    猜你喜欢
    • 1970-01-01
    • 2021-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-01
    • 1970-01-01
    相关资源
    最近更新 更多