Angular 测试 - 可观察管道不是函数

Angular testing - observable pipe is not a function

我想为照片上传方法编写单元测试。但是我收到 Failed: this.task.snapshotChanges(...).pipe is not a function TypeError: this.task.snapshotChanges(...).pipe is not a function 错误。

为了本题简单,我把代码全部放在一个方法里:

组件

  public startUpload(event: FileList) {
    const file: File = event.item(0);
    const pathRef = `users/${this.uid}`;

    this.task = this.service.uploadPhoto(pathRef, file);
    this.fileRef = this.service.getFileReference(pathRef);
    this.percentage = this.task.percentageChanges();
    this.snapshot = this.task.snapshotChanges();
    this.task.snapshotChanges().pipe(last(), switchMap(() => // it fails here - need to propperly mock this
    this.fileRef.getDownloadURL()))
      .subscribe(url => this.service.updatePhoto(url));
  }

Component.spec

  it('should upload file', async(() => {
    const supportedFile = new File([''], 'filename.png', {type: 'image/', lastModified: 2233});
    const fileList = {
      item: () => {
        return supportedFile;
      }
    };
    const spy = (<jasmine.Spy>serviceStub.uploadPhoto).and.returnValue({
      percentageChanges: () => of(null),
      snapshotChanges: () => {
        return {
          getDownloadURL() {
            return of(null);
          }
        };
      }
    });

    component.startUpload(<any>fileList);

    expect(spy).toHaveBeenCalledWith(`users/${component.uid}`, supportedFile);
  }));

使单元测试正常工作的解决方案是添加以下行: (<jasmine.Spy>service.getFileReference).and.returnValue({ getDownloadURL: () => of(null) });

据我了解,出现此错误是因为 this.task.snapshotChanges(...) return 是间谍中的 Object。 相反,它应该 return 和 Observable.

const spy = (<jasmine.Spy>serviceStub.uploadPhoto).and.returnValue({
  percentageChanges: () => of(null),
  snapshotChanges: () => {
    return of({
      getDownloadURL() {
        return of(null);
      }
    })
  }

});

此外,getDownloadURL: () => of(null) 也应该 return 可观察。