Ian Jamieson
Ian Jamieson

Reputation: 4816

Unit Testing fromEvent observable with withLatestFrom

I have the following observables:

  public ngAfterViewInit(): void {
    fromEvent(this.showFeaturesButton.nativeElement, 'click').pipe(
      takeUntil(this.ngUnsubscribe),
      withLatestFrom(this.store.pipe(select(fromClientStorage.getSubscription)))
    ).subscribe(([_event, subscription]) => {
      this.featureModal.open(FeatureListComponent, {
        data: {
          features: subscription.features
        },
      });
    });
  }

I am trying to test using:

   it('should call modal when feature button is clicked', () => {
      const subscription: Subscription = ClientMock.getClient().subscription;
      spyOn(instance['store'], 'pipe').and.returnValue(hot('-a', {a: subscription.features}));
      spyOn(instance.featureModal, 'open');
      instance.ngAfterViewInit();
      instance.showFeaturesButton.nativeElement.click();
      expect(instance.featureModal.open).toHaveBeenCalledWith(FeatureListComponent, {
        data: {
          features: subscription.features
        }
      });
    });

However I am never hitting the subscribe which opens the modal. If I remove withLatestFrom like this:

  public ngAfterViewInit(): void {
    fromEvent(this.showFeaturesButton.nativeElement, 'click').pipe(
      takeUntil(this.ngUnsubscribe)
    ).subscribe(res) => {
      this.featureModal.open(FeatureListComponent, {
        data: {
          features: res
        },
      });
    });
  }

Then subscribe is hit, I am just wondering what I am missing with withLatestFrom

Upvotes: 2

Views: 2008

Answers (1)

Kliment Ru
Kliment Ru

Reputation: 2137

it's becase withLatestFrom create subscription and get value on initiation before spyOn

switchMap + combineLatest fix this problem

public ngAfterViewInit(): void {
  fromEvent(this.showFeaturesButton.nativeElement, 'click').pipe(
    takeUntil(this.ngUnsubscribe),
    switchMap(ev => combineLatest(of(ev), this.store.pipe(select(fromClientStorage.getSubscription))))
  ).subscribe(([_event, subscription]) => {
    this.featureModal.open(FeatureListComponent, {
      data: {
        features: subscription.features
      },
    });
  });
}

Upvotes: 1

Related Questions