这次我试图模拟一个服务(执行 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);
});
}
}
文档(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');
});
});
当我运行测试时,我得到:
Error: No provider for AuthHttp!
这确实由实际服务使用,但不是由模拟。所以由于某种原因,没有注入或使用模拟。
有什么建议吗?谢谢!