在Angular中进行单元测试时,使用模拟服务返回2个不同的值 [英] Returning 2 different values using using a mock service while unit testing in Angular
问题描述
问题摘要:
如何在同一测试规范内使用同一服务调用多个值,并检查其是否与组件中的功能完全相同?
我正在使用Angular7 +.
I am using Angular7+.
让组件(例如A)中注入了服务.
Let there be a component ( say A ) with a service injected into it.
假设,在同一服务中有一个 getNumber 函数,具有两个参数,即("Key","Value"),其中键"只能是 num1 或 num2 ,值"可以是任何整数.
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.
此函数以以下格式返回对象: {键":num1或num2,值":数字} ,并且该对象存储在另一个对象中(例如总计)作为其元素.示例:
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};
现在在带有服务的组件的单元测试中,我有一个带有getNumber函数的模拟服务存根,并且我正在做类似的事情:
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'
我实际上希望这两个值可以结合起来,即在我的测试中, 我首先以"num1"作为键给出了12的返回值,然后以"num2"作为键给出了13的返回值,我期望输出为25(12 + 13).
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 ).
推荐答案
此方法有效.具有两个不同值的returnValues:
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);
这篇关于在Angular中进行单元测试时,使用模拟服务返回2个不同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!