monxas
monxas

Reputation: 2657

testing emit to have been called in karma not working

I have this method where the emit event should always be called:

changeDate() {
  let dateFrom = moment(this.dateFromControl.value, 'YYYY-MM-DD');
  let dateTo = moment(this.dateToControl.value, 'YYYY-MM-DD');
  const formDate = {
    dateFrom: moment(dateFrom).isValid() ? moment(dateFrom).format('YYYY-MM-DD') : '',
    dateTo: moment(dateTo).isValid() ? moment(dateTo).format('YYYY-MM-DD') : ''
  }
  this.dateForm.emit(formDate);
}

and this is the test for it:

it('should validate changeDate', (done) => {
  component.dateFromControl.patchValue('01-01-2020');
  component.dateToControl.patchValue('11-11-2020');

  component.changeDate();
  spyOn(component.dateForm, 'emit');
  expect(component.dateForm.emit).toHaveBeenCalled();
  done();

});

I'm getting expected spy emit to have been called, and I'm wondering what's wrong.

Upvotes: 0

Views: 1027

Answers (1)

Santi Barbat
Santi Barbat

Reputation: 2325

Try subscribing to the output instead:

it('should validate changeDate', (done) => {
  component.dateForm.subscribe(data => {
    expect(data.dateFrom).toBe('2020-01-01');
    expect(data.dateTo).toBe('2020-11-11');

    done();
  });

  component.dateFromControl.patchValue('01-01-2020');
  component.dateToControl.patchValue('11-11-2020');
  component.changeDate();
});

This way you not only test that the output has been called but that the data is correct.

Upvotes: 0

Related Questions