0

It may be that my components just aren't structured correctly, although they work as needed when running the app; I just can't get my test to pass.

Parent component (I'm using an ng-bootstrap modal; this function is called on a button click):

  openMyModal() {
    this.myModalRef = this._modalService.open(ExtractModalComponent); //this is what ng-bootstrap prescribes for opening their modals
    this.myModalRef.componentInstance.setRangeRequest.subscribe($e => {  
      this.setDateRange($e.fromDate, $e.toDate); //<== I'm trying to test that this is called
    });

child component has this output:

@Output() setRangeRequest = new EventEmitter()
...
clickHandler() {
  this.setRangeRequest.emit({ fromDate: this.fromDateTime, toDate: this.toDateTime });
}

And below is my parent component spec. I'm not sure if I've created the spy correct, and though the order of the act step seems right to me (code that subscribes to the observable, followed by emitting the event that was subscribed to), the test fails with cannot read property fromDate of undefined and if I switch those statements, and emit first, then the test fails with expected spy to be called with... but was never called.

it('should use dates returned from the modal in the service call', fakeAsync(() =>{
    //Arrange
    let dt = moment(new Date()).format();
    let modalSpy = spyOn(comp.myModalRef.componentInstance, 'setRangeRequest').and.returnValue(
      Observable.of({ fromDate: dt, toDate: dt })
    );

    //Act
    comp.openMyModal
    comp.myModalRef.componentInstance.downloadRequest.emit();
    tick();

    //Assert
    expect(eduExtractDataSpy).toHaveBeenCalledWith(comp.workingFile.loadId, dt, dt);
  })
);
redOctober13
  • 3,662
  • 6
  • 34
  • 61
  • just found this answer, but it's from such a long time ago, don't know if its directions to never subscribe to an event emitter are still valid: https://stackoverflow.com/questions/36076700/what-is-the-proper-use-of-an-eventemitter – redOctober13 Jan 31 '18 at 20:17
  • But as that post was made about a pre-release version of Angular 2, this seems to be more relevant now: https://stackoverflow.com/a/47167133/3406483. Doesn't solve the problem in question, but at least indicates I'm not completely wrong in trying to subscribe to the event emitter. – redOctober13 Feb 01 '18 at 13:23

0 Answers0