简体   繁体   English

Angular 2 EventEmitter显然在测试中不发光

[英]Angular 2 EventEmitter apparently not emitting in test

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. 今天多次阅读了《 Angular指南》之后,我无法通过测试,也无法弄清原因。

stackblitz example (of course here the spy expectation works, but not the other one) stackblitz示例 (当然,这里的间谍期望有效,但其他期望不起作用)

component.html component.html

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

component.ts 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. 在我看来,它几乎与指南中的示例完全一样,但是由于某些原因,他们的测试通过了,而我的却没有。

Well I feel sheepish... 好吧,我感到sheep脚...

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! 根据Angular指南,我使用Page类来避免在测试中查询元素,并且在设置页面时,我在download函数上创建了一个间谍,并完全隔开了它将始终使用的位置,因此download()被调用,里面没有东西!

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! 我知道这一定与测试环境有关!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM