vendredi 9 août 2019

Undefined value when trying to test RxJS interval

I am executing initializeTimer method in ngOnInit hook. In initializeTimer I defined rxjs interval which is responsible for decrementing number passed in component Input. Now I want to test this method, however I get an error

Expected undefined to equal 9.

I have no idea how can I test this subscription. I read something about fakeAsync and tick, but it seems not work for me. As form me ngOnInit is not triggered.

Component

@Input() timeLeft: number;
timer: number;
observableTimer: Subscription;

constructor() { }

ngOnInit() {
  this.initializeTimer();
}

initializeTimer() {
  this.observableTimer = interval(1000).subscribe(val => {
    const timeLeft = this.timeLeft - val;
    if (timeLeft === 0) {
      this.onTimesUp();
    }
    this.timer = timeLeft;
  });
}

Test

it('expect timer to decrement', fakeAsync(() => {
  component.timeLeft = 10;
  fixture.detectChanges();
  tick(1000);
  fixture.detectChanges();
  expect(component.timer).toEqual(9);
}));

Aucun commentaire:

Enregistrer un commentaire