【问题标题】:Angular2 - Open and close mdDialog in Unit TestAngular2 - 在单元测试中打开和关闭 mdDialog
【发布时间】:2018-01-11 14:39:09
【问题描述】:

我目前正在尝试在我的一个单元测试中打开和关闭 angular material 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() 函数?谢谢!

【问题讨论】:

  • 你得到哪个错误?
  • @yurzui "预期的间谍 afterDialogClose 已被调用。"
  • 还有2 timer(s) still in the queue.?
  • @yurzui 1 个计时器仍在队列中,是的

标签: angular unit-testing typescript angular-material2


【解决方案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

【讨论】:

  • 正确修复队列错误。但是仍然没有按预期调用 afterDialogClose 函数,这意味着对话框没有关闭
  • 你能在我的 plunker 中重现它吗?
猜你喜欢
  • 1970-01-01
  • 2017-08-11
  • 1970-01-01
  • 2022-08-18
  • 2020-01-06
  • 2013-02-23
  • 1970-01-01
  • 2018-01-16
  • 1970-01-01
相关资源
最近更新 更多