MarcoLe
MarcoLe

Reputation: 2509

Angular testing - observable pipe is not a function

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

Upvotes: 3

Views: 18308

Answers (2)

Amit Vishwakarma
Amit Vishwakarma

Reputation: 316

As per my understanding, this error is coming because this.task.snapshotChanges(...) returns an Object in the spy. Instead, it should return an Observable.

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

});

Also, getDownloadURL: () => of(null) should also return Observable.

Upvotes: 1

MarcoLe
MarcoLe

Reputation: 2509

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

Upvotes: 8

Related Questions