Unit Testing fromEvent observable with withLatestFrom

こ雲淡風輕ζ 提交于 2021-02-10 13:45:32

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/52623803/unit-testing-fromevent-observable-with-withlatestfrom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!