Angular testing - observable pipe is not a function

14,017

Solution 1

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

Solution 2

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.

Share:
14,017
MarcoLe
Author by

MarcoLe

Loves to spend his reputation points for useless bounties.

Updated on June 07, 2022

Comments

  • MarcoLe
    MarcoLe almost 2 years

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