【发布时间】: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 => { console.log($e.fromDate, $e.toDate); });在任何情况下,角度指南本身都会显示测试这样的子组件。
标签: javascript angular unit-testing testing eventemitter