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

如何解决TypeError: restoreDialogRef.afterClosed is not a function错误?

解决TypeError: restoreDialogRef.afterClosed is not a function问题

问题描述

测试ConfigurationRestoreComponent时触发错误:TypeError: restoreDialogRef.afterClosed is not a function,报错位置在openConfirmationDialog方法中调用restoreDialogRef.afterClosed().subscribe()的代码行(对应main.js:16303:22)。

错误原因

单元测试中模拟的mockedDialogRef对象仅定义了componentInstance属性,缺少afterClosed()方法的实现。而业务代码中明确调用了该方法订阅对话框关闭事件,导致调用不存在的方法抛出错误。

解决步骤

  • 给模拟的mockedDialogRef添加afterClosed()方法,返回一个可订阅的Observable(可使用of()创建空值Observable,或用Subject模拟对话框关闭行为)
  • 确保模拟对象结构与真实MatDialogRef的API对齐

修改后的单元测试代码

it('Should open confirmation dialog ', fakeAsync(() => {
  fixture = TestBed.createComponent(ConfigurationRestoreComponent);
  component = fixture.componentInstance;

  // 给mockedDialogRef添加afterClosed方法,返回空Observable
  const mockedDialogRef = { 
    componentInstance: { onRestore: new Subject<void>(), onCancel: new Subject<void>() },
    afterClosed: () => of({}) // 新增afterClosed方法实现
  };
  spyOn((component as any).dialog, 'open').and.returnValue(mockedDialogRef);
  spyOn(component, 'openConfirmationDialog').and.callThrough();
  spyOn(component, 'upload'); // 新增spy用于断言
  spyOn(component, 'onCancel'); // 新增spy用于断言

  component.openConfirmationDialog();
  mockedDialogRef.componentInstance.onRestore.next();
  mockedDialogRef.componentInstance.onCancel.next();
  tick(2000);
  fixture.detectChanges();

  expect(component.openConfirmationDialog).toHaveBeenCalled();
  expect(component.upload).toHaveBeenCalled();
  expect(component.onCancel).toHaveBeenCalled();
}));

扩展:模拟对话框关闭逻辑

如果需要测试对话框关闭后的业务逻辑,可使用Subject手动控制关闭事件:

const afterClosedSubject = new Subject<any>();
const mockedDialogRef = { 
  componentInstance: { onRestore: new Subject<void>(), onCancel: new Subject<void>() },
  afterClosed: () => afterClosedSubject.asObservable()
};

// 需要触发对话框关闭时调用
afterClosedSubject.next(/* 可选传入对话框返回值 */);
afterClosedSubject.complete();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 12:36:13