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

问题描述 投票:0回答:1

我如何在Angular Karma Jasmine单元测试中声明和利用接口?以下是错误信息,指出接口的第一个属性未定义;试图让组件运行]

无法读取未定义的'primaryPropertyMailingAddressId'的属性

业力/茉莉花:

 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();
  });

Component:

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;

资源:

How to unit test model interfaces in typescript?

angular typescript unit-testing karma-jasmine angular8
1个回答
1
投票

您需要初始化值:

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.