0

This is starting to feel bewitched. After having read the Angular guide multiple times today, I cannot get my test to pass, and cannot figure out why.

stackblitz example (of course here the spy expectation works, but not the other one)

component.html

<button (click)="download()" title="Save report to your computer">
  Download
</button>

component.ts

export class ExtractModalComponent implements OnInit {
  @Output() downloadRequest: EventEmitter<any> = new EventEmitter<any>();

  constructor(public activeModal: NgbActiveModal) {}

  download() {
    this.downloadRequest.emit({ fromDate: this.fromDateTime, toDate: this.toDateTime });
  }
}

component.spec.ts

it('should raise the downloadRequest event when the download button is clicked, and send the dates', () => {
  let dates = {};
  let spy = spyOn(comp.downloadRequest, 'emit');
  let dt = moment(new Date(2018, 0, 1, 13, 0, 0)).format();
  comp.downloadRequest.subscribe(result => {
    dates = result;
  });
  click(page.downloadBtn); //click helper borrowed from Angular guide; calls either el.click() or el.triggerEvent('click', eventObj)
  //have also tried just comp.download(), but that doesn't make a difference
  expect(spy).toHaveBeenCalled(); //fails: "Expected spy emit to have been called"
  expect(dates).toEqual({ fromDate: dt, toDate: dt }); //fails: Expected Object({  }) to equal Object({ fromDate: '2018-01-01T13:00:00-05:00', toDate: '2018-01-01T13:00:00-05:00' })
});

Any help would be greatly appreciated. To me it looks almost exactly like the example in the guides, but for some reason, their test passes and mine doesn't.

redOctober13
  • 3,662
  • 6
  • 34
  • 61
  • What is the parent component that listens for this event? I think you are testing on the wrong component? – Mike Tung Feb 01 '18 at 19:46
  • There is a parent component, but this component is a ng-bootstrap modal entry component, so the parent doesn't use the component's selector; it just opens the modal in code, and subscribes to the event: `this.extractModalRef.componentInstance.downloadRequest.subscribe($e => { console.log($e.fromDate, $e.toDate); });` In any case, the angular guide itself shows testing a child component like this. – redOctober13 Feb 01 '18 at 19:59

1 Answers1

0

Well I feel sheepish...

As per the Angular guides, I was using a Page class to avoid having to query elements in my tests, and in setting up the page, I created a spy on the download function, and completely spaced that it will always be used, so while download() was being called, nothing inside it was!

In any case, in an effort to solve this problem, I ended up moving code from the parent component to the child, since it really belonged there anyway, and eliminated the cross-talk and having to subscribe to the event. But that answers why it worked live and not in the test! I knew it had to be something about the test environment!

redOctober13
  • 3,662
  • 6
  • 34
  • 61