如何解决Angular项目Jest单元测试报Cannot read property of undefined错误
问题原因及修复方案
1. 拼写错误问题
首先排查模板和代码的属性名不一致问题:
- Editor-Dialog.html 中最后一个ngx-wig绑定的是
post.release.bus,但组件ts中定义的属性是bug,拼写不匹配会导致读取属性报错。 - 报错信息中出现的
enhancement(单数)和你代码中定义的enhancements(复数)不匹配,检查是否有其他位置写了单数的属性名。
2. 测试模拟数据结构问题
你在测试用例中直接覆盖了组件默认的post值,如果你的testPost没有完整定义嵌套的release属性,替换后post.release就会是undefined,此时模板读取post.release.features等属性自然会抛出报错。
请确保testPost的结构和组件定义的PostSection完全一致,示例如下:
const testPost: PostSection = { title: '测试标题', release: { features: '', enhancements: '', bug: '', }, blog: null, type: 1, };
3. 测试执行顺序优化
你当前的赋值时机是在组件实例创建之后才给component.post赋值,部分场景下第一次变更检测会先于赋值触发,稳妥的写法可以调整为:
it('should create', () => { const fixture = TestBed.createComponent(EditorDialogComponent); const component = fixture.componentInstance; // 先赋值再触发变更检测 component.post = testPost; fixture.detectChanges(); expect(component).toBeTruthy(); });
如果还是有问题,可以给模板的属性绑定加上可选链做兜底,避免空值报错:
<ngx-wig [(ngModel)]="post?.release?.features" formControlName="featuresDescription"> </ngx-wig>
额外优化建议
你当前三个ngx-wig控件都使用了同一个formControlName="enhancementDescription",每个表单控件需要对应唯一的formControlName,否则后续表单绑定会出现逻辑错误。
内容的提问来源于stack exchange,提问作者user9436741
相关产品推荐
相关产品推荐

