问题描述
我想为component.ts的.subscribe方法编写一个单元测试用例,该方法将订阅service.ts中的函数
这是component.ts
this.certificationFormservice.getWishlist({ id: this.empid
}).subscribe(data => {
this.wishlist = data as any;
this.wishlist.forEach(element => {
this.certIdList.push(parseInt(element.certification_id));
});
这是service.ts
getWishlist(data) {
return this.http.post(environment.apiUrl + '/api/wishlist/get',data).pipe(
tap(
response => this.ui.spin$.next(false),(error: any) => this.ui.spin$.next(false)
)
);
解决方法
创建模拟服务
export class MockCertificationFormservice{
getWishlist(param){
return of([certification_id: 1])
}
}
在 spec.ts 文件中的在useClass
内使用providers
:
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [HttpClientModule],declarations: [SomeComponent],providers: [{ provide: CertificationFormservice,useClass: MockCertificationFormservice}],}).compileComponents();
}));
// and then you'll get the "[certification_id: 1]" as a mocked response inside testing of component
我强烈建议您使用read this article of mine where I have explained it with more examples。作为初学者,您可以refer this collection of articles on unit testing进行单元测试时更加舒适