Angular 9 TestBed.inject & Provider Overrides
Asked Answered
B

2

11

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;
Brokenhearted answered 18/2, 2020 at 12:34 Comment(0)
A
11

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

Auscultate answered 18/2, 2020 at 12:43 Comment(2)
Thanks, my stubs will implement the same interface as the class they are a stub for but will have extras such as helper methods to make unit testing smoother. That's where the casting comes in to expose those extras.Brokenhearted
@C.Rodwell Alright, I understand. You can also think about exporting those functions from testing utilities, but I suppose that depends on the functions :)Auscultate
C
2
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);
  ...
});

Ref

Colophon answered 4/11, 2020 at 8:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.