如何在角组件与服务交互的地方使用茉莉花因果单元测试来测试.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进行单元测试时更加舒适

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...