在angular2中使用ts-mockito来模拟getter

时间:2017-09-08 13:59:09

标签: angular unit-testing

我有服务

@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模拟吸气剂?

1 个答案:

答案 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)
        }

    ]
});