Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between TestBed.get and new Service(...dependencies)

The angular guide demonstrates two different ways of testing, one by calling new Service() and providing the dependencies to the constructor directly, and the second using dependency injection by calling TestBed.get(Service).

Both of these seem functionally identical to me, except when I call TestBed.get() consecutively it does not call the constructor after the first call.

The angular documentation also mentions that TestBed.get() is deprecated (even though the guide still references it!) and that I should use Type or InjectionToken instead, but I do not see how either of these classes could replace TestBed.get().

like image 301
Justin Kavalan Avatar asked Jun 26 '19 15:06

Justin Kavalan


2 Answers

Deprecated from v9.0.0 use TestBed.inject

get(token: any, notFoundValue?: any): any

See how can we inject now:

describe('MyAmountComponent', () => {
  let component: MyAmountComponent;
  let fixture: ComponentFixture<MyAmountComponent>;
  let productService: ProductService;
  let orderService: OrderService;
  beforeEach(() => {
    TestBed.configureTestingModule({
       .....
    })
    .compileComponents();
    productService = TestBed.inject(ProductService);
    orderService = TestBed.inject(OrderService);
  });

Just adding so might can help someone.

like image 187
Ali Adravi Avatar answered Oct 05 '22 23:10

Ali Adravi


get is deprecated: from v9.0.0 use TestBed.inject (deprecation)

let valueServiceSpy: jasmine.SpyObj<ValueService>;

beforeEach(() => {
  const spy = jasmine.createSpyObj('ValueService', ['getValue']);

  TestBed.configureTestingModule({
    providers: [
      { provide: ValueService, useValue: spy }
    ]
  });
  // This is new way to inject Spied Service
  valueServiceSpy = TestBed.inject(ValueService) as jasmine.SpyObj<ValueService>; 
});

and then in tests

it('#getValue should return stubbed value from a spy', () => {
  valueServiceSpy.getValue.and.returnValue(yourValue);
  ...
});

Official Doc: https://v9.angular.io/guide/testing#angular-testbed

like image 35
Bhavin Avatar answered Oct 05 '22 23:10

Bhavin