可以通过withLatestFrom观察到来自Event的单元测试

时间:2018-10-03 09:23:38

标签: angular unit-testing observable ngrx

我有以下观察值:

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

我正在尝试使用:

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

但是,我从不点击打开模式的订阅。如果我这样删除withLatestFrom

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

然后订阅被点击,我只是想知道withLatestFrom

中缺少的内容

1 个答案:

答案 0 :(得分:1)

withLatestFrom创建订阅并在spyOn之前的启动中获取价值

switchMap + combineLatest解决此问题

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