Angular 9 TestBed.inject & Provider Overrides
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
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