我正在尝试在我的一个单元测试中打开和关闭角度材质2对话框。开场似乎很好,但是我监视一个应该在结束后调用的函数,并且它永远不会被调用,我认为这是因为对话框没有像我想要的那样关闭。
我要测试的代码:
openDialog() {
this.dialogRef = this.dialog.open( ConfirmationDialogComponent, {
height: '210px',
width: '335px',
disableClose: true
});
this.dialogRef.componentInstance.title = 'Delete Selected Intents?';
this.dialogRef.componentInstance.content = 'All corresponding data will be deleted';
this.dialogRef.componentInstance.option1 = 'Cancel';
this.dialogRef.componentInstance.option2 = 'Delete';
this.dialogRef.afterClosed().subscribe( result => {
this.afterDialogClose(result);
});
}
到目前为止我的测试(由于没有按预期调用afterDialogClose而失败):
it('should call afterDialogClose when the dialog closing event triggered', fakeAsync(() => {
spyOn(component, 'afterDialogClose');
component.openDialog();
fixture.detectChanges();
tick();
component.dialog.closeAll();
fixture.detectChanges();
tick();
expect(component.afterDialogClose).toHaveBeenCalled();
}));
有谁能告诉我我做错了什么以及如何强制我的对话框关闭并调用afterDialogClose()函数?谢谢!
答案 0 :(得分:1)
我认为主要错误是
队列中有1个计时器。
另见
要解决此问题,我们可以使用jasmine.done
代替async/fakeAsync
it('should call afterDialogClose when the dialog closing event triggered', (done) => {
spyOn(component, 'afterDialogClose');
component.openDialog();
fixture.detectChanges();
fixture.whenStable().then(() => {
component.dialog.closeAll();
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(component.afterDialogClose).toHaveBeenCalled();
done();
});
});
});
<强> Plunker Example 强>