Search code examples
angularangular-testangular9angular-unit-test

Angular 9 TestBed.inject & Provider Overrides


When using provider overrides what is the alternative of the following now that TestBed.get has been deprecated in Angular 9

TestBed.configureTestingModule({
  providers: [{ provide: MyClass, useClass: MyStub}]
});

const obj : MyStub = TestBed.get(MyClass);

Is it really this or is there a better way?

const obj : MyStub = TestBed.inject(MyClass) as unknown as MyStub;

Solution

  • For all intents and purposes, your MyStub should at least be a Partial or a class that extends the class it's trying to mock, otherwise your tests are kinda 'wrong', so if that's the case you can just do:

    const obj = TestBed.inject(MyClass);
    

    If you somehow will have different properties or different function signatures on your stub, you can also do this:

    const obj = TestBed.inject<MyStub>(MyClass as any);
    

    But generally speaking, your mocks should (partially) share the same signature as the thing it's mocking, which also means there is no need for casting