[英]Angular TestBed.inject type error when injecting into a spy
I want to inject a service into a serviceSpy in the same way as the angular example shows.我想以与 angular 示例所示相同的方式将服务注入到 serviceSpy 中。 Angular 9 https://angular.io/guide/testing#service-tests
角 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>
intellij 向我展示了这个错误 TS2322: Type 'ValueService' is
SpyObj<ValueService>
to type SpyObj<ValueService>
can someone help?有人可以帮忙吗?
I had same issue.我有同样的问题。 Accordingly to https://github.com/angular/angular/issues/35944 you may
根据https://github.com/angular/angular/issues/35944,您可以
valueServiceSpy = TestBed.inject(ValueService) as jasmine.SpyObj<ValueService>;
It worked for me :)它对我有用:)
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:
因此,如果您这样做,您将消除任何 TS 错误:
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".您基本上是在说“我将要传递一种您不知道的类型,但我希望您将其视为 blah blah 类型”。 That's my understanding of it.
这是我对它的理解。
尝试{ provide: ValueService, useValue: spy as any }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.