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

不羁的心 提交于 2020-06-06 08:28:25

问题


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?

I am using Angular7+.

Let there be a component ( say A ) with a service injected into it.

Suppose , there is a getNumber function in the same service with 2 parameters namely ( "Key" , "Value" ) where "Key" can only be either num1 or num2 and "Value" can be any integer.

This function returns an object in this format : { "Key" : num1 or num2 , "Value" : number } and this object is stored in another object ( say Total ) as its elements. Example :

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

Now in unit testing the component with the service, i have a mockService stub with a getNumber function and i am doing something like this :

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'

I actually wanted both the values to combine i.e in my test, i first gave a return value of 12 with " num1 " as key and then 13 with " num2 " as key, and i expected the output to be 25 ( 12 + 13 ).


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/61719672/returning-2-different-values-using-using-a-mock-service-while-unit-testing-in-an

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!