Angular Testing - 可观察管道不是函数

标签 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));
  }

组件.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) });

关于 Angular Testing - 可观察管道不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52607037/

相关文章:

javascript - 模拟 delay() RxJS 与 Jest

jquery - 我如何测试 Jasmine 中的 $scope.watch (AngularJS) 更改?

javascript - 卡在使用 RxJS 删除计数器应用程序中的所有内容

javascript - Angular - 模块 AppModule 导入的意外值 MatDialog

arrays - Angular-数组forEach索引

javascript - 来自给定选择器的 nodeList 的 Jasmine 测试事件监听器函数

javascript - 测试 Angular 中的 jasmine 是否调用了 $httpProvider.interceptors.push()

javascript - Rxjs throttleTime - 我们需要使用 asObservable 吗?

javascript - Typescript - 将拆分后的字符串推送到数组

angular - <router-outlet> 使 html 内容在 Angular 中消失