I have a service
@Injectable()
export class MyService {
private _id: string;
get id(): string {
return this._id;
}
}
And a test for a component, where I want to mock this service:
let myServiceMock = mock<MyService>(MyService);
when(myServiceMock.id).thenReturn('mockId');
TestBed.configureTestingModule({
imports: [
MyModule
],
providers: [
{
provide: MyService, useValue: instance(myServiceMock)
}
]
});
And when test is running, i get undefined
as an id
.
Is it possible to mock getters via mockito?
Looks like it is how TestBed.configureTestingModule
works. It redefines all dependencies which are provided as useValue
The solution is using useFactory
:
let myServiceMock = mock<myServiceMock>(MyService);
when(myServiceMock.id).thenReturn('mockId');
TestBed.configureTestingModule({
imports: [
MyModule
],
providers: [
{
provide: MyService, useFactory: () => instance(myServiceMock)
}
]
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With