角度测试-可观察的管道不起作用

时间:2018-10-02 11:01:44

标签: angular jasmine rxjs karma-jasmine angular-test

我想为一个照片上传方法编写一个单元测试。但是我收到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);
  }));

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

据我了解,由于this.task.snapshotChanges(...)在间谍中返回了Object,因此会出现此错误。 相反,它应该返回一个Observable

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

});

此外,getDownloadURL: () => of(null)还应该返回Observable。