【发布时间】:2020-02-12 12:45:46
【问题描述】:
我有一个组件订阅了由服务创建的全局扇出,我希望测试扇出是否确实被正确接收。所以,看看下面的代码,我想测试一下是否在 TestableComponent 中调用了 eventStartFanout$。
我知道代码实际上是通过“手动测试”来工作的 = 用我的眼睛,但我不知道如何将其转换为自动化测试。
我当前问题的最小化示例;
服务:
eventStartSubject = new Subject<any>();
eventStartFanout$ = this.eventStartSubject.asObservable();
function startEvent() {
this.eventStartSubject.next();
}
可测试组件:
ngOnInit() {
this.unchanged = true;
this.fanoutService.eventStartFanout$.subscribe(
_ => {
// Test that it reaches here when service triggers
this.changeVariable();
}
);
}
// Extra (unneeded) function to potentially help testing
function changeVariable(){
this.unchanged = false;
}
我目前的测试尝试:
beforeEach(() => {
fixture = TestBed.createComponent(TestableComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should do something when fanout happens', async(() => {
const fanoutService: FanoutService = TestBed.get(FanoutService);
component.unchanged = true;
spyOn(component, 'changeVariable');
// It should trigger the subscriber here and change component.unchanged
fanoutService.startEvent();
fixture.detectChanges();
expect(component.unchanged).toBeFalsy();
}));
【问题讨论】:
标签: angular testing jasmine karma-runner subscriber