Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 511
user3417377 Avatar asked Jul 25 '26 03:07

user3417377


1 Answers

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.

like image 169
Ritesh Waghela Avatar answered Jul 26 '26 18:07

Ritesh Waghela



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!