我有一个组件正在订阅由服务创建的全局扇出,并且我想测试扇出是否确实被正确接收。因此,请看下面的代码,我想测试是否在TestableComponent中调用了eventStartFanout $。
我知道代码实际上是通过做“手动测试”来工作的,=用我的眼睛,但是我不知道如何将其转换为自动测试。
我当前问题的最小示例;
服务:
eventStartSubject = new Subject<any>();
eventStartFanout$ = this.eventStartSubject.asObservable();
function startEvent() {
this.eventStartSubject.next();
}
testable-component:
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();
}));
比我想的要简单。解决方案是使用fakeAsync
和tick()
模拟订户可以执行更改的时间步,请参阅:
it('should do something when fanout happens', fakeAsync(() => {
const fanoutService: FanoutService = TestBed.get(FanoutService);
component.unchanged = true;
fanoutService.startEvent();
tick();
fixture.detectChanges();
expect(component.unchanged).toBeFalsy();
}));