当构造函数在服务内部调用函数时,Spyon不起作用。 总是在testcase中得到模拟服务响应。如果我将模拟服务返回数据设置为null,则得到该结果,在spyon之后,我需要抛出错误,当我这样做时,它会从productMockService下面获取一个值
这里我需要使用茉莉花测试下面的服务调用的不同场景,它已经编写了功能和功能,按预期工作。
但是失败场景无法测试,这没有进入可观察的错误方法。在真实服务中, 构造函数调用了该方法,而get访问器也调用了相同的方法来获取更新后的值。
在我给出的测试用例中,
测试用例:我正在使用useValue模拟服务。
it('should call the getproducts and get into error',()=>{
const app = fixture.componentInstance;
spyOn(productMockService, 'modeSetupStaticData').and.returnValue(
throwError(new Error( "Internal server Error" ))
);
(component as any).fetchProduct();
fixture.detectChanges();
expect(component.productType.length).toBe(undefined);
});
在上面的测试用例中,我已经将productType长度设置为2,因为已经在ProductMockService中设置了该长度,需要return value作为throw someError或某些值已更改,这总是从模拟服务获取数据。 spyon返回值。
在组件中。我将其称为fetchProduct并订阅并从服务中获取数据。
fetchProduct =() =>{
this.productMockService.modeSetupStaticData.subscribe(respose=>successProduct(data),
err=> failureProduct(err)
});
模拟服务:在模拟服务中,我已经获得了模拟产品资源库的数据形式。
`
export class productMockService{
modeSetupStaticData:Observable<any> =observableOf(
mockproductResponse.getProduct()
);
}
mockproductResponse.ts
static getProduct(){
return {
productType:[{productId:1,productType:'Mobiles',price:1000},{productId:1,productType:'laptops',price:1000}],
productLocation:[{productId:1,locationID:10001,location:chennai}]
}
ProductService:
@Injectable
export class ProductService{
private check = false;
get modeSetupStaticData():observable<any>{
this.fetchAllProducts();
}
constructor(){
this.fetchAllProducts();
}
fetchAllProducts():any()=>{
this.getproductService.fetchProductList.Subscribe(respose=>ProductSucess(data),
err=> ProductFailure(err)
});
private ProductFailure(err) :void(){
alert("Service has failed");
}
}
键入时语法关闭时会出现一些拼写错误,这是演示,实际代码受版权保护,因此无法发布,因此我创建了这样的情况。
问题:总是在特定的测试案例中获得模拟服务响应,如果有任何帮助表示赞赏,我将无法覆盖它。
在模拟服务响应中,给定null表示测试用例中为null,如果提供响应意味着得到响应,则无法使用spyon返回值更改响应。