2

I have a service which I'm consuming in my angular 2 unit test.

I call the service in the beforeEach block first with TestBed.get()

Example:

 beforeEach(() => {
    fixture = TestBed.createComponent(ConfigComponent);
    component = fixture.componentInstance;
    service = TestBed.get(ConfigService);
    fixture.detectChanges();
  });

I then use this service in the unit test like this:

Example:

 it('should do something', inject([ConfigService], (configService) => {
      // code here
 }));

Do I need to inject the service in the unit test If called previously, or do I need to just call TestBed.get() and the use it across or should I do both?

masterach
  • 437
  • 1
  • 6
  • 19

1 Answers1

3

As it's explained in this answer, inject and TestBed.get are similar, so it's a matter of style. Some services that are common to all specs can be assigned to variables, while services that are specific to particular specs can be injected only in those specs.

In the case when spec function relies on inject and not local variables, it doesn't have to be necessarily defined in the scope of current describe block and can be reused or moved to some helper function.

It should be noticed that injector instance is created on first inject function or TestBed.get call, the way they are used can alter the results.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565