如何解决如何在角组件与服务交互的地方使用茉莉花因果单元测试来测试.subscribe方法?
我想为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进行单元测试时更加舒适
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。