0
votes

How do I declare and utilize Interfaces in Angular Karma Jasmine unit test? The following is giving error, it is stating undefined for the first property of interface; trying to get the component running

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

Component:

export class PropertySitusFinalizeComponent implements OnInit {

  @Input() jsonData: PropertySitusAddressContainer;

Interface:

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;

Resource:

How to unit test model interfaces in typescript?

1
Can you post the complete code, preferably in a Stackblitz? Other than that, PropertySitusAddress does not seem to getting initialized and somewhere within your PropertySitusAddress you try to access it (component.propertySitusAddress.primaryPropertyMailingAddressId), hence an of undefined error pops up. (You do NOT need to initialize the values as jithil suggests, just a double-check that it's defined when you try to access it (!)Philipp Meissner

1 Answers

0
votes

You need to initialize the values:

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

this way, all the fields which accessed using . operators need to be initialized.

In your html, use value = "jsonData?.existingPropertySitusAddress?.primaryPropertyMailingAddressId" will be a good option for type safety.