简体   繁体   中英

Using ts-mockito in angular2 to mock getter

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) } ] }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM