如何在rxjs订阅方法调用中测试代码

时间:2018-09-03 22:03:01

标签: angular jasmine rxjs

所以我有一些这样的代码:

ngOnInit() {
  this.openDialogWhenUploading();
}

openDialogWhenUploading() {
    this.store.select(getFileIsUploading).pipe(
        takeUntil(this.onDestory$),
        delay(1000)
    ).subscribe(uploading => {
        if(uploading === true) {
            this.dialog.open()
        }
    })
}

使测试更容易的方法是从openDialogWhenUploading方法返回一个可观察的对象,然后在我的测试中订阅它,就像这样:

ngOnInit() {
  this.openDialogWhenUploading().subscribe();
}

openDialogWhenUploading() {
    return this.store.select(getFileIsUploading).pipe(
        takeUntil(this.onDestory$),
        delay(1000),
        tap(uploading => {
            if (uploading === true) {
                this.dialog.open()
            }
        })
    )
}

在我的测试中:

describe('openDialogWhenUploading', () => {
  it('should open dialog when uploading', () => {
    openDialogWhenUploading().subscribe(() => {
      expect(dialg.open).toHaveBeenCalled();
    })
  })
})

任何更好的解决方案?

1 个答案:

答案 0 :(得分:0)

我认为拥有filter会更好吗?由于函数名称已经暗示只有在操作上载时才能打开对话框:

openDialogWhenUploading() {
    this.store.select(getFileIsUploading)
        .pipe(
            takeUntil(this.onDestory$),
            delay(1000),
            filter(uploading=>uploading)
        );
}

您的测试非常好,应该保留。