Search code examples
angularunit-testingjasmineangular-dependency-injection

Angular TestBed.inject


I am doing angular unit testing. Does TestBed.inject(service) create a new instance of the service? I was always under the assumption that TestBed.configureTestingModule() created the service and by inject we just accessed a reference of the created service.


Solution

  • TestBed.configureTestingModule() helps you configure the providers. Configuring the providers means you are letting the Angular dependency injection system know about this dependency which later it can inject in to components when requested through a dependency injection token. In the below example the dependency and token is ValueService.

    TestBed.configureTestingModule({ providers: [ValueService] });
    

    Later, you can use ValueService in your test using TestBed.inject. When you say TestBed.inject Angular dependency injection system checks if there is a provider registered against the token, if yes, then it creates an instance of the service and returns it. If it doesn't find that token, you will the famous

    No provider for ValueService error.

    it('should use ValueService', () => {
      service = TestBed.inject(ValueService);
      expect(service.getValue()).toBe('real value');
    });
    

    So it is similar to our application code, where in we first configure the providers and then inject it to our components to grab an instance of that service.