我正在使用Observable进行事件订阅,但无法对其进行测试
这是我的代码
服务
export class EventService<T> {
private eventSubject = new Subject<string>();
eventSubject$ = this.eventSubject.asObservable();
dispathEvent(name) {
this.eventSubject.next(name);
}
}
组件
export class UserComponent implements OnInit{
getSub: Subscription;
constructor(private service EventService, private otherService OtherServece)(){}
ngOnInt(){
this.getSub = this.service.eventSubject$.subscribe(name =>{
this.otherService.performAction();
this.otherService.setVar = name;
})
}
}
规范文件
let mockEventService :any;
mockEventService = {
eventSubject: jasmine.createSpyObj('eventSubject', ['next']),
eventSubject$: jasmine.createSpyObj('eventSubject$', ['subscribe']),
};
//some code
providers: [{ provide: EventService, useValue: mockEventService }]
// some code
fixture = TestBed.createComponent(UserComponent);
component = new TeamOvertimeComponent(mockEventService ,mockOtherService);
....
it('should test ngOnInt Service var status', () => {
expect(mockEventService.eventSubject$['subscribe']).toHaveBeenCalled()
fixture.detectChanges();
//
component.ngOnInit();
});
我看到的问题是
TypeError: this.service.eventSubject$.subscribe is not a function
我尝试过将它们保留在每个位置,但仍然存在
答案 0 :(得分:2)
您需要从具有subscribe
方法的对象创建间谍,在这种情况下是可观察的:
mockEventService = {
eventSubject: jasmine.createSpyObj('eventSubject', ['next']),
eventSubject$: jasmine.createSpyObj('eventSubject$', ['subscribe']),
};
据我所知,其余的代码可以保持不变。您可以像这样监视它:
expect(mockOvertimeService.eventSubject$['subscribe']).toHaveBeenCalled()
要测试订阅块,您可以执行以下操作(未测试的代码):
mockEventService = {
eventSubject$: { subscribe: jasmine.createSpy().and.callFake((cb) => cb('test')) }
};
otherService = {
performAction: jasmine.createSpy()
};
fixture.detectChanges();
expect(mockEventService.eventSubject$['subscribe']).toHaveBeenCalled();
expect(otherService.performAction).toHaveBeenCalled();
expect(otherService.setVar).toBe('test');