【问题标题】:Angular 2 EventEmitter apparently not emitting in testAngular 2 EventEmitter 显然没有在测试中发射
【发布时间】:2018-02-01 19:42:26
【问题描述】:

这开始让人感到着迷。今天多次阅读Angular guide 后,我无法通过测试,也无法弄清楚原因。

stackblitz example(当然,间谍期望在这里有效,但不是另一个)

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

任何帮助将不胜感激。对我来说,它看起来几乎与指南中的示例一模一样,但出于某种原因,他们的测试通过了,而我的则没有。

【问题讨论】:

  • 监听这个事件的父组件是什么?我认为您正在测试错误的组件?
  • 有一个父组件,但是这个组件是一个ng-bootstrap模态入口组件,所以父组件不使用组件的选择器;它只是在代码中打开模式,并订阅事件:this.extractModalRef.componentInstance.downloadRequest.subscribe($e =&gt; { console.log($e.fromDate, $e.toDate); }); 在任何情况下,角度指南本身都会显示测试这样的子组件。

标签: javascript angular unit-testing testing eventemitter


【解决方案1】:

嗯,我觉得很害羞……

根据 Angular 指南,我使用 Page 类来避免在我的测试中查询元素,并且在设置页面时,我在下载功能上创建了一个间谍,并完全隔开它总是会被使用,所以当 download() 被调用时,里面什么都没有!

无论如何,为了解决这个问题,我最终将代码从父组件移动到子组件,因为无论如何它确实属于那里,并且消除了串扰和订阅事件。但这回答了为什么它在现场而不是在测试中有效!我知道这一定与测试环境有关!

【讨论】:

    猜你喜欢
    • 2020-12-04
    • 2019-12-04
    • 1970-01-01
    • 2018-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-10
    • 1970-01-01
    相关资源
    最近更新 更多