Angular component test cases getting error : Type Error : Cannot read property "contractno" of undefined

Angular component test cases getting error : Type Error : Cannot read property "contractno" of undefined

在尝试注入 运行 规范文件所需的默认依赖项时出错较少 像类型错误:无法读取未定义的 属性 "contractno"

/** Class 用户模型**/

export class UserModel {
  contractNo: string;
  firstName: string;
  lastName: string;
  phoneNo: string;
  emailAddress:string;
}

这里是组件文件 /**contactus 组件**/

    import {
      Component,
      OnInit,
      ViewChild,
      Pipe,
      PipeTransform
    } from "@angular/core;
    import { UserModel } from "../models/User-model.model";
    import { HttpClient } from "@angular/common/http";
    import { Router } from "@angular/router";
    import { ContactUsService } from "../service/contact-us.service";
    import { Subscription } from "rxjs";
  export class ContactUsComponent implements OnInit {
      public contactModel: UserModel; 
      constructor(
        private http: HttpClient,
        private router: Router,
        private contactusservice: ContactUsService
      ) {
      }
      ngOnInit() {
        this.loadDefaultUser();
      }
      loadDefaultUser() {
         this.charRemaining = 1000;
         this.contactusmodel = JSON.parse(sessionStorage.getItem("data"));       
      }
        }

这里是组件测试用例文件 /**联系我们-spec.ts **/

import { async, ComponentFixture, TestBed } from "@angular/core/testing";
import { ContactUsComponent } from "./contact-us-component";
import { RouterTestingModule } from "@angular/router/testing";
import { DebugElement, Pipe, PipeTransform } from "@angular/core";
import { FormsModule } from "@angular/forms";
import { NumberPipePipe } from "./number-pipe.pipe";
import { HttpClient } from "@angular/common/http";
import { HttpClientTestingModule } from "@angular/common/http/testing";
import { UserModel } from "../models/User-model.model";
import { ContactUsService } from "../service/contact-us.service:;

describe("ContactUsComponent", () => {
  let component: ContactUsComponent;
  let fixture: ComponentFixture<ContactUsComponent>;
  let debugElement: DebugElement;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ContactUsComponent, NumberPipePipe],
      imports: [RouterTestingModule, FormsModule, HttpClientTestingModule],
      providers: [ContactUsServices, UserModel ]
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(PostLoginContactUsComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it("should create", () => {
    expect(component).toBeTruthly();
  });
});

fixture.detectChanges();触发组件的渲染。我赌 HTML 你用 contactModel.contractno。由于从未设置 contactModel,因此由于描述的错误,测试无法呈现组件。

解决方案是在 fixture.detectChanges(); 之前设置 contactModel,或者以这种方式调整 HTML,这样只有在 contactModel 有价值时才会调用它。