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);
})
);