Angular16升级后Jasmine测试PrimeNG Dialog遇WindowMaximizeIcon报错
Angular 16升级后PrimeNG Dialog组件Jasmine测试失败:WindowMaximizeIcon未知元素
问题场景
将Angular应用从15版本升级至16版本后,针对包含PrimeNG <Dialog>组件的IncidentGridComponent执行Jasmine测试时,触发如下错误:
Chrome 114.0.0.0 (Windows 10) IncidentGridComponent should launch window when addItemClicked is called ... FAILED
Error: NG0304: 'WindowMaximizeIcon' is not a known element (used in the 'Dialog' component template):
- If 'WindowMaximizeIcon' is an Angular component, then verify that it is a part of an @NgModule where this component is declared.
- To allow any element add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.
error properties: Object({ code: 304 })
at validateElementIsKnown (node_modules/@angular/core/fesm2022/core.mjs:6000:23)
at ɵɵelementStart (node_modules/@angular/core/fesm2022/core.mjs:15286:9)
at Module.ɵɵelement (node_modules/@angular/core/fesm2022/core.mjs:15361:5)
at templateFn (node_modules/primeng/fesm2022/primeng-dialog.mjs:866:84)
at executeTemplate (node_modules/@angular/core/fesm2022/core.mjs:10959:17)
at renderView (node_modules/@angular/core/fesm2022/core.mjs:12158:13)
at TemplateRef.createEmbeddedViewImpl (node_modules/@angular/core/fesm2022/core.mjs:22990:9)
at ViewContainerRef.createEmbeddedView (node_modules/@angular/core/fesm2022/core.mjs:23255:37)
at NgIf._updateView (node_modules/@angular/common/fesm2022/common.mjs:3316:45)
at NgIf.set ngIf [as ngIf] (node_modules/@angular/common/fesm2022/common.mjs:3289:14)
解决方案
方案1:导入PrimeNG图标模块
PrimeNG 16中,Dialog组件内部使用的WindowMaximizeIcon属于独立的IconsModule模块。在测试配置中导入该模块即可解决元素识别问题:
import { TestBed } from '@angular/core/testing'; import { IncidentGridComponent } from './incident-grid.component'; import { DialogModule } from 'primeng/dialog'; import { IconsModule } from 'primeng/icons'; describe('IncidentGridComponent', () => { beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [IncidentGridComponent], imports: [ DialogModule, IconsModule // 添加图标模块到测试导入列表 ] }).compileComponents(); }); // 测试用例逻辑 });
方案2:添加NO_ERRORS_SCHEMA(临时兼容)
如果不想导入图标模块,可以通过NO_ERRORS_SCHEMA让Angular忽略未知元素的校验,但该方案会屏蔽所有未知元素的错误提示,仅适合临时调试使用:
import { TestBed } from '@angular/core/testing'; import { IncidentGridComponent } from './incident-grid.component'; import { DialogModule } from 'primeng/dialog'; import { NO_ERRORS_SCHEMA } from '@angular/core'; describe('IncidentGridComponent', () => { beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [IncidentGridComponent], imports: [DialogModule], schemas: [NO_ERRORS_SCHEMA] // 添加到测试模块的schemas列表 }).compileComponents(); }); // 测试用例逻辑 });
原因说明
Angular 16升级后,PrimeNG调整了组件依赖结构,Dialog组件的最大化按钮使用的WindowMaximizeIcon不再包含在DialogModule中,必须单独导入IconsModule,才能让Angular在测试环境中识别该元素。
内容的提问来源于stack exchange,提问作者Phil Huhn
相关产品推荐
相关产品推荐

