When constructing my MaintainCOCComponent
, I include a parameter for the MaintainCOCService
which contains the API call method service.
export class MaintainCOCComponent {
constructor(private maintaincocservice: MaintainCOCService) { }
}
Using Constructor Injection:
In this approach, I configure the testBed and inject a mock service MockMaintainCOCService
via provider.
TestBed.configureTestingModule({
imports: [FormsModule, RouterTestingModule.withRoutes([])],
declarations: [MaintainCOCComponent],
providers: [
{ provide: MaintainCOCService, useClass: MockMaintainCOCService }]
});
Using SpyOn Injection
In this scenario, I create a mock of the real service using SpyOn functionality.
providers: [
{ provide: MaintainCOCService, useClass:MaintainCOCService }]
_maintainCOCService = fixture.componentRef.injector.get(MaintainCOCService);
spyOn(_maintainCOCService, 'Method1')
.and.callFake(function (key, value) {
return 1;
});
spyOn(_maintainCOCService, 'Method2')
.and.callFake(function (key, value) {
return 2;
});
Instead of mocking every method using SpyOn, we can directly pass the mock service in the provider. So when should we use Constructor Injection and when should we use SpyOn Injection? Which approach is considered as best practice?