【问题标题】:How to fix TypeError Cannot read property of undefined如何修复 TypeError 无法读取未定义的属性
【发布时间】: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


【解决方案1】:

在使用各个变量之前添加 ngIf 条件,以确保变量可用。

例如,

<ngx-wig *ngIf="post && post.release"
          [(ngModel)]="post.release.features"></ngx-wig>

【讨论】:

    【解决方案2】:

    { 提供:MAT_DIALOG_DATA,使用值:{} } 在这里你应该通过testPost

    【讨论】:

      【解决方案3】:

      进行以下更改,一切顺利:

      <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
      

      【讨论】:

        猜你喜欢
        • 2019-08-19
        • 2021-10-03
        • 2022-01-12
        • 2022-11-22
        • 2019-12-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-05
        相关资源
        最近更新 更多