本文介绍了使用LatestFrom可以观察到来自事件的单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下观察值:

  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 :

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

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

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

推荐答案

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

这篇关于使用LatestFrom可以观察到来自事件的单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 07:02