Angular 2:如何测试订阅(命令性)组件中的事件发射器?

时间:2018-01-31 20:06:04

标签: angular unit-testing observable eventemitter

可能是我的组件结构不正确,尽管它们在运行应用程序时可以根据需要运行;我无法通过测试。

父组件(我正在使用ng-bootstrap模式;点击按钮时会调用此函数):

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

子组件有此输出:

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

以下是我的父组件规范。我不确定我是否已经创建了间谍正确,虽然 act 步骤的顺序似乎对我来说(订阅了observable的代码,然后发出订阅的事件) ),测试以cannot read property fromDate of undefined失败,如果我切换这些语句并先发出,那么测试将失败并显示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);
  })
);

0 个答案:

没有答案