使用CombineLatest测试组件

时间:2019-06-26 15:30:15

标签: angular rxjs jest

尝试对具有rxjs选择器的combineLatest Ngrx调用的组件进行单元测试。我似乎找不到模拟返回数据的方法。

我尝试使用jasmine-marblesof()似乎都不刷新数据。

功能

private onSelectedCard(selectedCard: Card) {
    this.selectedCard = selectedCard;
    if (this.selectedCard !== undefined) {
      this.storeSelectLatest$ = combineLatest(
        this.store.pipe(select(fromBacklog.getListById(this.selectedCard.planId, this.selectedCard.listId))),
        this.store.pipe(select(fromBacklog.getPlanById(this.selectedCard.planId))),
        this.store.pipe(select(fromBacklog.getPlans)),
        (list, plan, plans) => ({ list, plan, plans }),
      );

      this.storeSelectLatest$.pipe(takeUntil(this.unsubscribe$)).subscribe(({ list, plan, plans }) => {
        this.listWithSelectedCard = list;
        this.activeListsOnPlanWithSelectedCard = [...plan.lists.filter(listInPlan => listInPlan.id !== 0 && listInPlan.active)];
        this.plansLoaded = plans;
        const cardIndex: number = list.cards.findIndex(card => card.id === this.selectedCard.id);
        const listIndex: number = this.activeListsOnPlanWithSelectedCard.findIndex(l => l.id === list.id);
        const planIndex: number = plans.findIndex(p => p.id === plan.id);

        this.canMoveUp = cardIndex > 0 || planIndex > 0 || listIndex > 0;

        this.canMoveDown =
          (cardIndex >= 0 && cardIndex < list.cards.length - 1) ||
          planIndex < plans.length - 1 ||
          listIndex < this.activeListsOnPlanWithSelectedCard.length - 1;
      });
    }
  }

测试

it('should highlight all the buttons for a selected card in the middle of the list', async(() => {
      component.storeSelectLatest$ = cold('-a', { a: { list: mockList, board: mockBoard, boards: [mockBoard] } });

      component['onSelectedCard'](mockCard);

      getTestScheduler().flush();
      fixture.detectChanges();
      expect(component.canMoveUp).toBeTruthy();
    }));

也尝试过

it.only('should highlight all the buttons for a selected card in the middle of the list', async(() => {
      component.storeSelectLatest$ = of({ list: mockList, board: mockBoard, boards: [mockBoard] });

      component['onSelectedCard'](mockCard);

      expect(component.canMoveUp).toBeTruthy();
    }));

期待测试通过。 相反,我得到

  

TypeError:您提供了一个无效对象,该对象应用于流。   您可以提供一个Observable,Promise,Array或Iterable。

1 个答案:

答案 0 :(得分:0)

FWIW,ngrx 8允许您模拟选择器:

https://medium.com/ngrx/announcing-ngrx-version-8-ngrx-data-create-functions-runtime-checks-and-mock-selectors-a44fac112627

如果您不想升级,我建议通过模拟对6/11/19的调用来解决此问题,并让它们返回您选择的观察值。也就是说,升级在意义上来说是微不足道的代码更改并提供大量价值。