3

I am getting TypeError: cannot read property 'id' of undefined when trying to perform unit test in my angular 8 application.

Here is my template

<h4>{{student.id}}</h4>

Here is my component

import {Component, EventEmitter, Input, OnInit} from '@angular/core';
import { Student } from '@app/app-types';

@Component({
...... saved some typing
})

export class StudentComponent implements OnInit {
@Input() student: Student;
refreshForm: EventEmitter<any>;

constructor(){}

ngOnInit(){
  this.refreshForm = new EventEmitter();
  }
}

and here is the unit test

import {async, ComponentFixture, TestBed } from '@angular/core/testing';
import {StudentComponet} from './student-component';

describe('StudentComponet', () => {
  let component: StudentComponent;
  let fixture: ComponentFixture<StudentComponent>;
  
  beforeEach(async(() => {
  TestBed.configureTestingModule({
    declarations: [StudentComponent]
  }).compileComponents();
  }));
  
  beforeEach(() => {
    fixture = TestBed.createComponent(StudentComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });
  
  it('should create', () => {
  expect(component).toBeTruthy();
  })
  
  });
sage poudel
  • 357
  • 4
  • 14

1 Answers1

6

use

student?.id

in unit test you have to provide value for student

beforeEach(() => {
  ...
  component.student = value;
  fixture.detectChanges();
);
Damian Pioś
  • 473
  • 2
  • 5