[英]Angular 2 EventEmitter apparently not emitting in test
這開始讓人感到困惑。 今天多次閱讀了《 Angular指南》之后,我無法通過測試,也無法弄清原因。
stackblitz示例 (當然,這里的間諜期望有效,但其他期望不起作用)
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 });
}
}
組件規格
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' })
});
任何幫助將不勝感激。 在我看來,它幾乎與指南中的示例完全一樣,但是由於某些原因,他們的測試通過了,而我的卻沒有。
好吧,我感到sheep腳...
根據Angular指南,我使用Page類來避免在測試中查詢元素,並且在設置頁面時,我在download函數上創建了一個間諜,並完全隔開了它將始終使用的位置,因此download()
被調用,里面沒有東西!
無論如何,為了解決這個問題,我最終將代碼從父組件移到了子組件,因為它實際上確實屬於該組件,並且消除了串擾並必須訂閱事件。 但這回答了為什么它可以實時運行而不在測試中起作用的原因! 我知道這一定與測試環境有關!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.