我得到以下错误

  1. 应打开确认对话框

ts文件如下所示

openConfirmationDialog() 
{
    const restoreDialogRef = this.dialog.open(RestoreConfirmationComponent, {
      restoreFocus: false,
      width: '37.5rem',
    });
    const dialogCallOnrestore = restoreDialogRef.componentInstance.onRestore
      .pipe(takeUntil(this.destroy$))
      .subscribe(() => {
        this.upload(this.formData);
      });

    const dialogCallOncancel = restoreDialogRef.componentInstance.onCancel
      .pipe(takeUntil(this.destroy$))
      .subscribe(() => {
        this.onCancel();
      });

    restoreDialogRef.afterClosed().subscribe(() => {
      dialogCallOnrestore.unsubscribe();
      dialogCallOncancel.unsubscribe();
    });
  }

spec.ts文件如下

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

    const mockedDialogRef = { componentInstance: { onRestore: new Subject<void>(), onCancel: new Subject<void>() } };
    spyOn((component as any).dialog, 'open').and.returnValue(mockedDialogRef);
    spyOn(component, 'openConfirmationDialog').and.callThrough();
    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;
  }));

    const matDialogSpy = jasmine.createSpyObj('MatDialogRef.componentInstance', ['onReset', 'onCancel']);
    TestBed.configureTestingModule({
      imports: [FormsModule, MatTabsModule, ReactiveFormsModule, MatDialogModule,CiqTestingModule],
      declarations: [SettingsIntegratedGatewayComponent],
      providers: [
        { provide: MAT_DIALOG_DATA, useValue: {} },
        { provide: MatDialogRef, useValue: matDialogSpy },
        { provide: MatDialog, useValue: dialogMock },
        { provide: SettingsEsrsService, useValue: settingsEsrsService },
      ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
    })
      .overrideProvider(InteractivityChecker, {
        useValue: {
          isFocusable: () => true,
        },
      })
      .compileComponents();
    matDialogRef = TestBed.get(MatDialogRef);
  }));

你知道如何解决这个问题吗?

推荐答案

你在模仿dialog对象open方法.

spyOn((component as any).dialog, 'open').and.returnValue(mockedDialogRef);

返回mockedDialogRef个对象,其中包含componentInstance个对象及其方法.它还应该返回afterClosed方法模拟实现.

const mockedDialogRef = { 
   componentInstance: { 
     onRestore: new Subject<void>(),
     onCancel: new Subject<void>(), 
   },
   afterClosed: () => new Subject<void>(), // <- provide fake function for afterClosed.
};

Angular相关问答推荐

添加@ nx/webpack插件 destruct 了Nativescript构建

如何在HTMLTITLE属性中使用Angular 显示特殊字符?

更改动态表单控制Angular 的值

如何使用formBuilder.Group()从角形表单中删除选定的选项?

使用Dragula时,ReactiveForm元素在拖动副本中显示不同的