【发布时间】:2021-10-28 08:25:41
【问题描述】:
我正在尝试在我的 Angular 项目中使用 Jest 编写单元测试用例,当我尝试运行我的测试文件时遇到这些错误
TypeError: Cannot read property 'features' of undefined
TypeError: Cannot read property 'enhancement' of undefined
TypeError: Cannot read property 'bug' of undefined
我在我的 HTML 文件中读取这些属性,我想如果我在侧面 spec.ts 文件中创建一个模拟数据,那么它应该修复它,但我不确定为什么我仍然会收到这些错误。
Editor-Dialog.component.ts
export class EditorDialogComponent implements OnInit {
post: PostSection = {
title: '',
release: {
features: null,
enhancements: null,
bug: null,
},
blog: null,
type: 1,
};
在我的 Editor-Dialog.html 中,我是这样阅读的
<ngx-wig
[(ngModel)]="post.release.features"
formControlName="enhancementDescription"></ngx-wig>
<ngx-wig
[(ngModel)]="post.release.enhancements"
formControlName="enhancementDescription"></ngx-wig>
<ngx-wig
[(ngModel)]="post.release.bus"
formControlName="enhancementDescription"></ngx-wig>
这是我的测试文件Editor-Dialog.spec.ts的sn-p
// I have created mock data in this file
it('should create', () => {
const fixture = TestBed.createComponent(EditorDialogComponent);
const component = fixture.componentInstance;
component.post = testPost;
fixture.detectChanges();
expect(component).toBeTruthy();
});
我已在此处上传了这些组件的完整代码,因此如果有人可以查看它并帮助我修复它,即使您将无法运行该项目,我将不胜感激。
https://stackblitz.com/edit/angular-ivy-dv2dha?file=editor-dialog.html
【问题讨论】:
-
你不应该在同一个元素中使用 ngModel 和 formControl。要么你使用 ngModel 要么 formControl。
-
您是否尝试过逐步调试代码+测试?哪一行抛出错误? testPost 长什么样子?
-
可能是 testPost 不包含预期数据
标签: angular typescript unit-testing testing jestjs