Тестовый компонент с использованием combLatest - PullRequest
0 голосов
/ 26 июня 2019

Попытка модульного тестирования компонента, который имеет вызов rxjs combineLatest для селекторов Ngrx.Кажется, я не могу найти способ высмеять возвращенные данные.

Я пытался использовать jasmine-marbles и of(), похоже, ни один из них не сбрасывает данные.

function

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 голосов
/ 26 июня 2019

FWIW, ngrx 8 позволяет вам смоделировать селекторы:

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

Если вы не хотите обновляться, я бы рекомендовал обойти это, насмехаясь над вызовами store.pipe, и заставить их возвращать наблюдаемую информацию по вашему выбору. Тем не менее, обновление довольно тривиально с точки зрения изменений кода и предлагает массу пользы.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...