Reputation: 38683
My Componenet MaintainCOCComponent
constructor have an parameter for MaintainCOCService
which is have API call method service.
export class MaintainCOCComponent {
constructor(
private maintaincocservice: MaintainCOCService) { }
}
Here i have configured testBed and injected with a mock MockMaintainCOCService
service via provider
TestBed.configureTestingModule({
imports: [FormsModule, RouterTestingModule.withRoutes([])],
declarations: [MaintainCOCComponent],
providers: [
{ provide: MaintainCOCService, useClass: MockMaintainCOCService }]
});
Here I have mocked that real service by using SpyOn.
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;
});
we can directly pass the mock service in provider instead of mocking every method using spyon.So which scenario we want use Constructor injection and which scenario we want to use Spyon Injection? and and which one is best?
Upvotes: 0
Views: 124
Reputation: 35563
Usually, when ever you need to mock the entire service, you will use the Constructor Injection
mock, for example, you have a service that uses FB SDK on its internals, you don't want that your tests will go "out" to FB, so usually the best practice it to build a mock Service that implements the same interface and mock it in the entire app.
The spyOn
method usually is use-full when you need to check some service that got the correct params. what that service doe's after the function call is usually not so interesting.
Small Note, sometimes the usage of spyOn
can indicate that you are testing the implementation rather then the specification.
Upvotes: 1