Angular testing - observable pipe is not a function

MarcoLe picture MarcoLe · Oct 2, 2018 · Viewed 10.5k times · Source

I want to write a unit test for a photo-upload-mehtod. But I get the Failed: this.task.snapshotChanges(...).pipe is not a function TypeError: this.task.snapshotChanges(...).pipe is not a function Error.

For the sake of simplicity of this question, I put the code all in one method:

Component

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

Answer

MarcoLe picture MarcoLe · Oct 2, 2018

The solution for the unit test to get work was by adding this line: (<jasmine.Spy>service.getFileReference).and.returnValue({ getDownloadURL: () => of(null) });