Angular Karma Jasmine 中的单元测试接口:无法读取未定义的 属性 *

Angular Unit Test Interfaces in Karma Jasmine : Cannot Read Property * of Undefined

如何在 Angular Karma Jasmine 单元测试中声明和使用接口?以下是给出错误,它为接口的第一个 属性 声明未定义;试图获取组件 运行

Cannot read property of 'primaryPropertyMailingAddressId' of undefined

Karma/Jasmine:

 beforeEach(async(() => {

    fixture = TestBed.createComponent(PropertySitusFinalizeComponent);
    component = fixture.componentInstance;

    component.jsonData = {};  // removing or keeping this line does not change the error message

    fixture.detectChanges();

  }));

  it('should create', () => {
    expect(component).toBeTruthy();
  });

分量:

export class PropertySitusFinalizeComponent implements OnInit {

  @Input() jsonData: PropertySitusAddressContainer;

接口:

export interface PropertySitusAddressContainer {
  queueItemId?: number;
  existingPropertySitusAddress?: PropertySitusAddress;  

export class PropertySitusAddress {

    primaryPropertyMailingAddressId?:number = null;
    propertyId?: number = null;
    propertySitusAddressId?: number = null;
    addressFormatId?: number = null; 
    apn?: string = null;

资源:

您需要初始化值:

@Input() jsonData: PropertySitusAddressContainer = { existingPropertySitusAddress = {} }

这样,所有使用.操作符访问的字段都需要初始化。

在您的 html 中,使用 value = "jsonData?.existingPropertySitusAddress?.primaryPropertyMailingAddressId" 将是 type safety 的一个不错的选择。