You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 2+中如何测试MatDialog关闭时调用resend方法?

如何测试MatDialog关闭时resend方法是否被调用?

我需要测试当MatDialog关闭时,resend方法是否被调用,该如何实现?

业务代码

private openResendDialog(id: number) {
  const matAlertDialog = this.dialog.open(MatAlertDialogComponent, {
    disableClose: true,
    data: {
      message: this.translateService.instant('table.resend_message'),
      type: 'confirm',
    },
  });
  matAlertDialog.afterClosed()
    .pipe(takeUntil(this.destroyed$))
    .subscribe(result => {
      if (result) {
        this.resend(id);
      }
    });
}

已编写的测试代码(SPEC.TS)

it('#openResendDialog', () => {
  const openResendDialogSpy = spyOn(component.dialog,'open').and.returnValue({
    afterClosed:() => of([1]),
  } as MatDialogRef<typeof component>);
  const fakeParam = {
    disableClose: true,
    data: {
      message: translateServiceMock.instant('table.resend_message'),
      type: 'confirm',
    },
  };
  component['openResendDialog'](1);
  fixture.detectChanges();
  expect(openResendDialogSpy).toHaveBeenCalledWith(MatAlertDialogComponent,fakeParam);
})

解决方案

要验证对话框关闭时resend方法是否被调用,你需要完成以下步骤:

  1. 创建resend方法的监听Spy:通过spyOn监听组件的resend方法,追踪它的调用状态和传入参数。
  2. 模拟对话框关闭的返回值:业务代码中仅当result为真值时触发resend,因此要让afterClosed()返回of(true)来模拟用户确认的场景;也可以用of(false)验证取消场景下resend不被调用。
  3. 添加断言验证调用情况:调用openResendDialog后,断言resend的调用状态和参数是否符合预期。

修改后的测试代码示例

it('#openResendDialog should call resend when dialog closes with confirm', () => {
  // 1. 监听resend方法
  const resendSpy = spyOn(component, 'resend');
  
  // 2. 模拟对话框关闭返回true
  const openSpy = spyOn(component.dialog, 'open').and.returnValue({
    afterClosed: () => of(true),
  } as MatDialogRef<MatAlertDialogComponent>);

  const testId = 1;
  component['openResendDialog'](testId);
  fixture.detectChanges();

  // 验证对话框打开参数正确
  const expectedConfig = {
    disableClose: true,
    data: {
      message: translateServiceMock.instant('table.resend_message'),
      type: 'confirm',
    },
  };
  expect(openSpy).toHaveBeenCalledWith(MatAlertDialogComponent, expectedConfig);
  
  // 验证resend被调用且参数正确
  expect(resendSpy).toHaveBeenCalledOnceWith(testId);
});

// 额外验证:取消对话框时resend不触发
it('#openResendDialog should NOT call resend when dialog closes with cancel', () => {
  const resendSpy = spyOn(component, 'resend');
  
  spyOn(component.dialog, 'open').and.returnValue({
    afterClosed: () => of(false),
  } as MatDialogRef<MatAlertDialogComponent>);

  component['openResendDialog'](1);
  fixture.detectChanges();

  expect(resendSpy).not.toHaveBeenCalled();
});

关键注意点

  • 若resend是私有方法,需用spyOn(component, 'resend' as any)来创建监听(根据TypeScript配置调整)。
  • 监听Spy必须在调用openResendDialog之前创建,否则无法捕获调用行为。

内容的提问来源于stack exchange,提问作者Rotenberg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 01:50:25