0

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.

monxas
  • 2,475
  • 2
  • 20
  • 36
  • 1
    For one thing you spy *after* taking the action. But assuming you're talking about an @Output there are much better ways to test it than checking the emit method got called, see e.g. https://stackoverflow.com/a/62871934/3001761 – jonrsharpe Dec 14 '20 at 08:25
  • @jonrsharpe it's not an output but yeah, I was not calling the spy before the function... I hate mondays. Thanks! – monxas Dec 14 '20 at 08:37
  • 1
    Still, spying on part of the thing you're supposed to be testing is a smell, think about how else you could assert on the outcome. – jonrsharpe Dec 14 '20 at 08:38
  • @jonrsharpe I understand where you're coming from, the code above is a simplified version of the whole method that was relevant to the problem I was facing. THanks for your concerns! – monxas Dec 14 '20 at 08:42

1 Answers1

1

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.

Santi Barbat
  • 2,097
  • 2
  • 21
  • 26