1

I started to write unit tests and have some issue. Test failed with error TypeError: Cannot set property 'birthday' of undefined

Maybe someone can give an advise how to make it work correctly. Would be really grateful for any help!

My code:

CandidateItemComponent.ts

export class CandidateItemComponent implements OnInit {

  @Input() candidate: Candidate;
  @Input() isAdmin: boolean;
  birthday: string;

  ngOnInit() {
    this.birthday = this.candidate.birthday;
  }
}

CandidateItemComponent.html

<div *ngFor="let property of visibleCandidateProperties"
     class="candidate-item"
     [attr.title]="property.propertyKey === 'age' ? birthday : ''">
  {{candidate[property.propertyKey]}}
</div>

CandidateItemComponent.spec.ts

import { async, ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';
import { CandidateItemComponent } from './candidate-item.component';

describe('CandidateItemComponent', () => {
  let component: CandidateItemComponent;
  let fixture: ComponentFixture<CandidateItemComponent>;
  const mockIsAdmin = true;
  const mockBirthday = '12-07-1997';

  const mockCandidate = {
    id: 2,
    firstName: 'Alexander',
    lastName: 'Osichanskiy',
    email: '[email protected]',
    phone: '380638732626',
    birthday: '12-07-1997',
  };

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [CandidateItemComponent],
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(CandidateItemComponent);
    component = fixture.debugElement.componentInstance;
    component.isAdmin = mockIsAdmin;
    component.birthday = mockBirthday;
    fixture.detectChanges();
  });

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

});

1 Answer 1

2

that's because you also need to set the candidate input along with other inputs,

it('should create', () => {
    expect(component).toBeTruthy();
    component.isAdmin = mockIsAdmin;
    component.birthday = mockBirthday;

    component.candidate = mockCandidate;         // here

    fixture.detectChanges();
  });
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for this. The error message literally could not be any worse.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.