Angular 18独立组件单元测试报错:Cannot read properties of undefined (reading 'ɵcmp')
解决Angular 18独立组件单元测试中「Cannot read properties of undefined (reading 'ɵcmp')」报错
报错信息
Chrome 128.0.0.0 (Windows 10) DashboardComponent should create FAILED TypeError: Cannot read properties of undefined (reading 'ɵcmp') at getComponentDef (node_modules/@angular/core/fesm2022/testing.mjs:1563:18) at isStandaloneComponent (node_modules/@angular/core/fesm2022/testing.mjs:1559:17) at forEach (node_modules/@angular/core/fesm2022/testing.mjs:1322:29) at Array.forEach (<anonymous>) at queueTypesFromModulesArrayRecur (node_modules/@angular/core/fesm2022/testing.mjs:1317:34) at forEach (node_modules/@angular/core/fesm2022/testing.mjs:1323:29) at Array.forEach (<anonymous>) at queueTypesFromModulesArrayRecur (node_modules/@angular/core/fesm2022/testing.mjs:1317:34) at TestBedCompiler.queueTypesFromModulesArray (node_modules/@angular/core/fesm2022/testing.mjs:1332:9) at TestBedCompiler.configureTestingModule (node_modules/@angular/core/fesm2022/testing.mjs:833:18) Chrome 128.0.0.0 (Windows 10): Executed 1 of 29 (1 FAILED) (skipped 28) (0.124 secs / 0.105 secs) TOTAL: 1 FAILED, 0 SUCCESS
解决方案
修正TestBed配置中独立组件的位置
独立组件不能放在imports数组中,需移至declarations,或者直接通过TestBed.createComponent初始化:
错误示例:TestBed.configureTestingModule({ imports: [DashboardComponent], // 错误:独立组件不应放入imports providers: [MyService] });正确示例1:
TestBed.configureTestingModule({ declarations: [DashboardComponent], providers: [MyService] });正确示例2(Angular 14+简洁写法):
await TestBed.configureTestingModule({ providers: [MyService] }).compileComponents(); const fixture = TestBed.createComponent(DashboardComponent);确认组件的独立属性配置
检查DashboardComponent的装饰器是否包含standalone: true,这是独立组件的核心标识:@Component({ selector: 'app-dashboard', standalone: true, // 必须配置此属性 templateUrl: './dashboard.component.html', styleUrls: ['./dashboard.component.css'] }) export class DashboardComponent {}若未配置该属性,需将组件对应的NgModule导入到测试配置的
imports数组中。清理缓存后重新执行测试
缓存异常可能导致此类错误,执行以下命令清理缓存并重新测试:ng cache clean ng test --no-cache检查依赖服务的配置正确性
若依赖服务使用providedIn: 'root',无需重复提供;若需Mock服务,确保正确提供Mock实例:TestBed.configureTestingModule({ declarations: [DashboardComponent], providers: [ { provide: MyService, useValue: { /* 定义Mock方法/属性 */ } } ] });
内容的提问来源于stack exchange,提问作者Valentina Maronese
相关产品推荐
相关产品推荐

