我正在尝试对具有注入(inject)服务的Angular组件进行单元测试。在组件的构造函数中,调用注入(inject)服务上的方法,该方法返回Observable。我正在尝试在组件的单元测试中模拟服务,但我一直遇到此错误:TypeError: Cannot read property 'subscribe' of undefined
。
我尝试通过以下方式模拟服务:
const serviceStub = {
getObservable: () => { return {subscribe: () => {}}; },
};
beforeEach(async(() => {
TestBed.configureTestingModule({
providers: [
{provide: MyService, useValue: serviceStub}
]
})
it('should create', () => {
spyOn(serviceStub, 'getObservable').and.returnValue({subscribe: () => {}});
expect(component).toBeTruthy();
});
感觉好像我缺少明显的东西。有人可以指出吗?
更新
即使在测试台提供商中注入(inject)实际服务时,也会出现此错误。
组件的构造函数如下所示:
private _subscription: Subscription;
constructor(private _service: MyService) {
this._subscription = _service.getObservable().subscribe(console.log);
}
最佳答案
使用注入(inject)来注入(inject)服务并模拟它而不是 stub
it('should create', inject([MyService], (myService: MyService) => {
spyOn(myService, 'getObservable').and.returnValue({subscribe: () => {}});
expect(component).toBeTruthy();
}));
这是完整版本:
成分:
@Component({
selector: 'my-cmp',
template: 'my cmp {{x}}'
})
export class MyComponent {
x;
constructor(private myService: MyService) {
this.myService.getObservable()
.subscribe(x => {
console.log(x);
this.x = x;
});
}
}
测试:
describe('my component test', () => {
let fixture: ComponentFixture<MyComponent>, comp: MyComponent, debugElement: DebugElement, element: HTMLElement;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [MyComponent],
providers: [MyService]
});
}));
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
comp = fixture.componentInstance;
debugElement = fixture.debugElement;
element = debugElement.nativeElement;
});
it('should create', inject([MyService], (myService: MyService) => {
expect(comp).toBeTruthy();
}));
it('should set value', async(inject([MyService], (myService: MyService) => {
spyOn(myService, 'getObservable').and.returnValue(Observable.of(1));
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(comp.x).toEqual(1);
});
})));
});