Reputation: 91
I was looking through the tests cases written by my team members.
What I have noticed was that at some cases they have used TestBed.inject(serviceName)
for injecting the Service while in others they have used fixture.debugElement.injector.get(serviceName)
.
Can somebody tell me the difference between this two? And also, what is the correct way of injecting services in my specs?
For eg:
let abc: ABCService
Technique 1:
abc = TestBed.inject(ABCService)
Technique 2:
abc = fixture.debugElement.injector.get(ABCSerice)
Upvotes: 9
Views: 3023
Reputation: 18849
I think they are essentially the same thing. I only use Technique 1
.
In older versions of Angular, it was TestBed.get
but now it is TestBed.inject
.
I think TestBed.inject
gets the service from the root injector while fixture.debugElement.injector.get
gets the service that is actually injected into the component.
You can read more about it here.
You can provider a service in the Component
decorator of a Component
and each instance of this service will be unique (a separate instance) and I bet fixture.debugElement.inject.get
will get this unique instance provided in the decorator as opposed to the global singleton. Check out providers in decorators here.
Upvotes: 11