单元测试间隔和switchMap

时间:2020-02-04 16:18:57

标签: angular unit-testing testing rxjs switchmap

我有一个具有以下ngOnInit函数的组件,该组件轮询服务方法以进行状态更新:

ngOnInit() {
this.waitingForMachineToStart = interval(2000)
  .pipe(
    distinctUntilChanged(),
    switchMap(() => this.machineService.getMachineStatus(this.machineId)),
  )
  .subscribe(res => {
    this.machineStatus = res.status;
    if (this.machineStatus === 'STARTED') {
      this.machineStarted = res
      this.notify()
    }
  });
}

我正在尝试使用以下代码测试更新是否确实在发生:

beforeEach(() => {
  fixture = TestBed.createComponent(UploadComponent);
  component = fixture.componentInstance;
  fixture.detectChanges();
});


it('should start checking for status updates', fakeAsync(() => {
  const machineService = TestBed.get(MachineService);
  spyOn(machineService, 'getMachineStatus').and.returnValue(Observable.create().pipe(map(() => {status :'STARTED'})));
  // Should not be initialised yet
  expect(component.machineStarted).toBeUndefined();
  tick(2000);
  //FAILING TEST
  expect(component.machineStarted).toBe({status :'STARTED'});
}));

但是,测试仍然失败。

预先感谢

0 个答案:

没有答案