模拟组件中的服务 - 模拟被忽略

you*_*uri 15 service mocking angular2-testing angular

这次我试图模拟一个服务(做http调用)来测试一个组件.

@Component({
  selector: 'ub-funding-plan',
  templateUrl: './funding-plan.component.html',
  styleUrls: ['./funding-plan.component.css'],
  providers: [FundingPlanService]
})
export class FundingPlanComponent implements OnInit {
  constructor(private fundingPlanService: FundingPlanService) {
  }

  ngOnInit() {
    this.reloadFundingPlans();
  }

  reloadFundingPlans() {
    this.fundingPlanService.getFundingPlans().subscribe((fundingPlans: FundingPlan[]) => {
      this.fundingPlans = fundingPlans;
    }, (error) => {
      console.log(error);
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

文件(2.0.0版本)解释说,你应该嘲笑的服务.使用相同的TestBed配置:

describe('Component: FundingPlan', () => {
  class FundingPlanServiceMock {
    getFundingPlans(): Observable<FundingPlan> { return Observable.of(testFundingPlans) }
  }

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [FundingPlanComponent],
      providers: [
        { provide: FundingPlanService, useClass: FundingPlanServiceMock },
      ]
    });

    fixture = TestBed.createComponent(FundingPlanComponent);
    component = fixture.componentInstance;
  });

  fit('should display a title', () => {
    fixture.detectChanges();
    expect(titleElement.nativeElement.textContent).toContain('Funding Plans');
  });

});
Run Code Online (Sandbox Code Playgroud)

当我运行测试时,我得到:

Error: No provider for AuthHttp!
Run Code Online (Sandbox Code Playgroud)

这确实是由实际服务使用,而不是模拟.因此,出于某种原因,模拟不会被注入或使用.

有什么建议吗?谢谢!

Pau*_*tha 44

这是因为

@Component({
  providers: [FundingPlanService] <===
})
Run Code Online (Sandbox Code Playgroud)

@Component.providers在全球任何供应商的优先级,因为使用@Component.providers的供应商范围的只对部分品牌.在测试中,Angular在模块范围中创建模拟服务,在组件范围中创建原始服务.

为了解决这个问题,Angular提供了TestBed.overrideComponent方法,我们可以在组件级别覆盖模板和提供程序之类的东西.

TestBed.configureTestingModule({
  declarations: [FundingPlanComponent]
});
TestBed.overrideComponent(FundingPlanComponent, {
  set: {
    providers: [
      { provide: FundingPlanService, useClass: FundingPlanServiceMock },
    ]
  }
})
Run Code Online (Sandbox Code Playgroud)

也可以看看:

  • 提供的链接非常有用,但它有点破碎.你的意思是这个吗?[覆盖组件的提供者](https://angular.io/guide/testing#override-a-components-providers) (2认同)