Difference between Testbed.inject(serviceName) and fixture.debugElement.injector.get(serviceName) in Angular Unit Testing

Viewed 1040

I was going through the test cases written by my team members. What I observed was at some places they've used TestBed.inject(serviceName) for injecting the service and at some places they've used fixture.debugElement.injector.get(serviceName). Can somebody tell me the difference between these two? Also what is the correct way of injecting services?

For eg:

let abc: ABCService

Technique 1: abc = TestBed.inject(ABCService) Technique 2: abc = fixture.debugElement.injector.get(ABCSerice)

Thanks in Advance

1 Answers

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.

Related