首页 > 解决方案 > Angular CDK 模态对话框的 Jasmine 规范失败

问题描述

我正在为我的 CanDeactivate Guard(它使用服务启动 Angular CDK 覆盖)创建 Jasmine 规范。这是规范文件:

class MockGuardComponent implements ComponentCanDeactivate {
  // Set this value to the value you want to mock being returned from 
GuardedComponent
  returnValue: boolean | Observable<boolean>;

  canDeactivate(): boolean | Observable<boolean> {
    return this.returnValue;
  }
}

describe('PendingChangesGuard', () => {
  let mockGuardComponent: MockGuardComponent;
  let service: PendingChangesGuard;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [PendingChangesGuard, MockGuardComponent, Overlay],
    });
    service = TestBed.get(PendingChangesGuard);
    mockGuardComponent = TestBed.get(MockGuardComponent);
  });

  it('should expect service to instantiate', () => {
    expect(service).toBeTruthy();
  });

  it('can route if unguarded -- form is not dirty', () => {
    mockGuardComponent.returnValue = true;
    expect(service.canDeactivate(mockGuardComponent)).toBeTruthy();
  });

  it('will open the confirm dialog', () => {
    mockGuardComponent.returnValue = false;
    expect(service.canDeactivate(mockGuardComponent)).toBeFalsy();
    expect(service.openConfirmDialog).toHaveBeenCalled();
  });
});

这是PendingChangesGuard文件:

export class PendingChangesGuard
  implements CanDeactivate<ComponentCanDeactivate> {
  constructor(private modalDialogService: ModalDialogService) {}

  canDeactivate(
    component: ComponentCanDeactivate
  ): boolean | Observable<boolean> {
    return component.canDeactivate() || this.openConfirmDialog();
  }

  openConfirmDialog() {
    const ref = this.modalDialogService.open(ModalDialogComponent, null);
    return ref.afterClosed$();
  }
}

警卫工作完美。问题是当我运行测试时出现此错误:

✗ will open the confirm dialog
    Error: No component factory found for ModalDialogComponent. Did you add it to @NgModule.entryComponents?

而且我肯定将它添加到Core模块的entryComponents中,而不是AppModule中。为什么测试会触发此错误?

标签: angular

解决方案


以防万一其他人遇到此问题,您必须像这样覆盖规范文件中的模块:

TestBed.configureTestingModule({
  providers: [
    PendingChangesGuard,
    MockGuardComponent,
    Overlay,
  ],
}).overrideModule(BrowserDynamicTestingModule, {
  set: {
    entryComponents: [ModalDialogComponent],
  },
});

推荐阅读