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

2
  • Is student one time instanciated ? Commented Jul 30, 2019 at 5:51
  • @FrV Yes. The student is received from the parent component via ngrx/store . Commented Jul 30, 2019 at 5:55

1 Answer 1

6

use

student?.id

in unit test you have to provide value for student

beforeEach(() => {
  ...
  component.student = value;
  fixture.detectChanges();
);
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for the reply. Can you please share how can I get that component.student = value dynamically, instead of hardcoding the value?
like value from backend?
Not really. What should I give the value in component.student = value ? As the student imported in component is an interface.
stackoverflow.com/questions/32628864/… here you have how to implements interfaces inline

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.