angular - 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中。为什么测试会触发此错误?
解决方案
以防万一其他人遇到此问题,您必须像这样覆盖规范文件中的模块:
TestBed.configureTestingModule({
providers: [
PendingChangesGuard,
MockGuardComponent,
Overlay,
],
}).overrideModule(BrowserDynamicTestingModule, {
set: {
entryComponents: [ModalDialogComponent],
},
});
推荐阅读
- python - 使用过滤器python抓取动态网站
- setuptools - 如何使用 main 方法配置 setup.py 工作?
- php - 使用 PHP 在 MSSQL 中查询用户数据
- ansible - Ansible win_package 在安装 PowerShell 7 MSI 时永远卡住
- python - 将字典插入到 sqlite3 数据库 - python
- elasticsearch - 嵌套聚合结果为空,但调试器中有数据
- sql - 当我在 nodejs 中使用 sequelize 进行 groupby 时,我得到计数为 1 而不是 0
- lua - 使用多个同名局部变量时的垃圾收集
- flutter - 如何将小部件返回到以前的状态
- javascript - 添加简单的 onclick 事件和 javascript 函数时出现错误的引导按钮