Returning 2 different values using using a mock service while unit testing in Angular

前端 未结 2 1111
栀梦
栀梦 2020-12-12 06:21

Summary of the issue :

How to call multiple values using the same service inside the same test spec and check to see if it works exactly as in the component?

相关标签:
2条回答
  • 2020-12-12 07:12

    This worked.. returnValues with 2 different values:

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

    0 讨论(0)
  • 2020-12-12 07:18

    Try this code.

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

    0 讨论(0)
提交回复
热议问题