0

I have the following Angular service method

  updateStorage(): void {
    this.authServiceRef = this.authService.authRequest('storage', {}).subscribe((result) => {
      this.storage = this.buildStorage(result);
      this.storageUpdate.emit({ ...this.storage });
    });
  }

and facing difficulties to test that piece of code

My test looks like

  fit('Update Storage Status', inject([AuthService], fakeAsync((authService: AuthService) => {
    spyOn(authService, 'authRequest').and.returnValue(Observable.of(storageStatus_50GB_LowUsageTest));
    spyOn(storageService, 'buildStorage');
    spyOn(storageService.storageUpdate, 'emit');

    
    storageService.updateStorage();
    tick(1000);


    expect(authService.authRequest).toHaveBeenCalledOnceWith('files', 'storage', {});
    expect(storageService.buildStorageStatus).toHaveBeenCalledTimes(1);
    expect(storageService.storageStatusUpdate.emit).toHaveBeenCalledTimes(1);

    //  FAILS - storageService.storage is undefined
    expect(storageService.storage.size).toEqual(storageStatus_50GB_LowUsageTest.size)
    expect(storageService.storage.maximum).toEqual(storageStatus_50GB_LowUsageTest.maximum);
    expect(storageService.storage.usedPercentage).toEqual(0.4)
    expect(storageService.storage.storageUsedSafeRound).toEqual(4);

  })));

All spy calls are fine and they pass but the storageService.storage is undefined

How to test the code inside a subscription function?

Kaloyan Stamatov
  • 3,894
  • 1
  • 20
  • 30
  • Does this answer your question? [Unit testing an observable in Angular 2](https://stackoverflow.com/questions/34607990/unit-testing-an-observable-in-angular-2) – Vikas Jan 10 '22 at 13:08

1 Answers1

1

Using spyOn on the buildStorage method will replace the called method with a stub (which will return undefined). In this case you want to use the callThrough or and.returnValue to ensure it returns the value you are expecting

Jelle
  • 2,026
  • 1
  • 12
  • 17