Как проверить несколько последовательных звонков с Жасмин - PullRequest
0 голосов
/ 29 января 2019

Я пытаюсь протестировать функцию, которая отписывается от всех подписок:

ngOnDestroy() {
        this.tryUnsubscribe(this.carsSubscription);
        this.tryUnsubscribe(this.partsSubscription);
        this.tryUnsubscribe(this.shopsSubscription);
    }

Это тест, который я написал для функции:

it('should unsubscribe from subscriptions ', () => { 
      spyOn(component, "tryUnsubscribe");     
      component.ngOnDestroy();
      expect(component.tryUnsubscribe).toHaveBeenCalledWith(component['carsSubscription']);
      expect(component.tryUnsubscribe).toHaveBeenCalledWith(component['partsSubscription']);
      expect(component.tryUnsubscribe).toHaveBeenCalledWith(component['shopsSubscription']);
    });

Проблема:

Если я закомментирую вызов функции, тесты все равно пройдут.

ngOnDestroy() {
        this.tryUnsubscribe(this.carsSubscription);
        //this.tryUnsubscribe(this.partsSubscription);
        this.tryUnsubscribe(this.shopsSubscription);
    }

Только если я закомментирую все эти вызовы функций, тест не пройден:

ngOnDestroy() {
        //this.tryUnsubscribe(this.carsSubscription);
        //this.tryUnsubscribe(this.partsSubscription);
        //this.tryUnsubscribe(this.shopsSubscription);
    }

Какправильно проверить этот вид функции?Что я делаю не так?

1 Ответ

0 голосов
/ 29 января 2019

Я бы переписал ваш тест следующим образом:

it('should unsubscribe from subscriptions ', () => { 
  const spy = spyOn(component, 'tryUnsubscribe');     
  component.ngOnDestroy();

  // Check how many times the spy was called
  expect(spy).toHaveBeenCalledTimes(3);
});

Если вы сейчас раскомментируете один из вызовов tryUnsubscribe, тест должен завершиться неудачей, поскольку шпион вызывался только дважды.

Другой подход заключается в том, чтобы смоделировать подписки или просто установить для них фиктивное значение, чтобы проверить, что внутри ngDestroy tryUnsubscribe вызывается с этими тремя компонентными переменными:

it('test unsubscribing', () => {
  // Mock values
  component.carsSubscription = Observable.of(1).subscribe(() => {});
  component.partsSubscription = Observable.of(1).subscribe(() => {});
  component.shopsSubscription = Observable.of(1).subscribe(() => {});

  const spy = spyOn(component, 'tryUnsubscribe').and.callThrough();     
  component.ngOnDestroy();

  // Check how many times the spy was called
  expect(spy).toHaveBeenCalledTimes(3);

  // Check arguments
  expect(spy.calls.all()[0].args[0]).toEqual(component.carsSubscription);
  expect(spy.calls.all()[1].args[0]).toEqual(component.partsSubscription);
  expect(spy.calls.all()[2].args[0]).toEqual(component.shopsSubscription);
});

Здесь - рабочий стек с тестом.

...