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

Mar*_*oLe 3 jasmine rxjs karma-jasmine angular 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));
  }
Run Code Online (Sandbox Code Playgroud)

组件.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);
  }));
Run Code Online (Sandbox Code Playgroud)

Mar*_*oLe 7

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