Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJS - Unit testing mergeMap inner Observable

Tags:

angular

rxjs

I have the following code:

  createAsset(asset: Asset): void {
    this._assetsService.uploadFile()
    .pipe(
      mergeMap(_ => this._assetsService.createAsset({
        ...asset,
        extension: 'png'
      })),
      take(1)
    )
    .subscribe(_ => {}, _ => console.error(_));
  }

And I would like to ensure that whenever this function is called, and it calls createAsset with the right parameters.

I did write a UT using Karma and Jasmine:

it('...', async (async () => {
    const assetsService = TestBed.inject(AssetsService);
    const uploadSpy = spyOn(assetsService, 'uploadFile').and.returnValue(of());
    const createSpy = spyOn(assetsService, 'createAsset').and.returnValue(of());

    const extension = 'png';

    const asset = {
      name: 'name',
      extension: null
    };

    component.createAsset(asset);

    await fixture.whenStable();
    expect(uploadSpy).toHaveBeenCalled();
    expect(createSpy).toHaveBeenCalledWith({...asset, extension}); // Error : This is never called
  }));

The inner obversable from the mergeMap createSpy is never called. Is there something I am missing ?

like image 890
Scipion Avatar asked Dec 02 '25 10:12

Scipion


1 Answers

 const uploadSpy = spyOn(assetsService, 'uploadFile').and.returnValue(of());

the issue lies in the mock using a Observable<void> simply replacing it by anything other than void fixed the issue.

like image 124
Scipion Avatar answered Dec 04 '25 04:12

Scipion



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!