Angular TestBed.inject type error when injecting into a spy

Viewed 2904

I want to inject a service into a serviceSpy in the same way as the angular example shows. Angular 9 https://angular.io/guide/testing#service-tests

let masterService: MasterService;
let valueServiceSpy: jasmine.SpyObj<ValueService>;

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

TestBed.configureTestingModule({
// Provide both the service-to-test and its (spy) dependency
providers: [
  MasterService,
  { provide: ValueService, useValue: spy }
]
});
// Inject both the service-to-test and its (spy) dependency
masterService = TestBed.inject(MasterService);
valueServiceSpy = TestBed.inject(ValueService);
});

intellij shows me this error TS2322: Type 'ValueService' is not assignable to type SpyObj<ValueService>

can someone help?

3 Answers

I don't know if you have found a solution to this yet, but I just faced the same issue and someone explained it to me - you have to cast it as unknown first and then cast it as something specific. So you'd eliminate any TS errors if you do this:

valueServiceSpy = TestBed.inject(ValueService) as unknown as jasmine.SpyObj<ValueService>;

You're basically saying "I am about to pass a type that you don't know, but I want you to treat it as type blah blah". That's my understanding of it.

Try { provide: ValueService, useValue: spy as any }

Related