Mocking service in component - mock is ignored

This time I'm trying to make fun of a service (which makes http calls) to test the component.

@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); }); } } 

the documentation (version 2.0.0) explains that you should mock the service. Using the same TestBed configuration:

 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'); }); }); 

When I run the test, I get:

 Error: No provider for AuthHttp! 

which is actually used by the actual service, but not the layout. Therefore, for some reason, the layout is not introduced and not used.

Can I advise? Thanks!

+7
angular service mocking angular2-testing
source share
1 answer

This is because

 @Component({ providers: [FundingPlanService] <=== }) 

@Component.providers takes precedence over any global providers, since using @Component.providers makes the provider tied to the component. In the test, Angular creates a mocked service in the module area and a source service in the component area.

To solve this problem, Angular provides a TestBed.overrideComponent method where we can redefine things like templates and providers

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

See also:

+19
source share

All Articles