我有服务
@Injectable()
export class MyService {
private _id: string;
get id(): string {
return this._id;
}
}
对组件的测试,我想模拟这项服务:
let myServiceMock = mock<MyService>(MyService);
when(myServiceMock.id).thenReturn('mockId');
TestBed.configureTestingModule({
imports: [
MyModule
],
providers: [
{
provide: MyService, useValue: instance(myServiceMock)
}
]
});
当测试运行时,我将undefined
作为id
。
是否可以通过mockito模拟吸气剂?
答案 0 :(得分:6)
看起来TestBed.configureTestingModule
的工作原理。它重新定义了以useValue
解决方案正在使用useFactory
:
let myServiceMock = mock<myServiceMock>(MyService);
when(myServiceMock.id).thenReturn('mockId');
TestBed.configureTestingModule({
imports: [
MyModule
],
providers: [
{
provide: MyService, useFactory: () => instance(myServiceMock)
}
]
});