最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - TypeError: cannot read property 'id' of undefined - Angular 8 Testing - Stack Overflow

matteradmin6PV0评论

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>

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 ponent

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-ponent';

describe('StudentComponet', () => {
  let ponent: StudentComponent;
  let fixture: ComponentFixture<StudentComponent>;
  
  beforeEach(async(() => {
  TestBed.configureTestingModule({
    declarations: [StudentComponent]
  }).pileComponents();
  }));
  
  beforeEach(() => {
    fixture = TestBed.createComponent(StudentComponent);
    ponent = fixture.ponentInstance;
    fixture.detectChanges();
  });
  
  it('should create', () => {
  expect(ponent).toBeTruthy();
  })
  
  });

Share Improve this question asked Jul 30, 2019 at 5:44 sage poudelsage poudel 3574 silver badges14 bronze badges 2
  • Is student one time instanciated ? – FrV Commented Jul 30, 2019 at 5:51
  • @FrV Yes. The student is received from the parent ponent via ngrx/store . – sage poudel Commented Jul 30, 2019 at 5:55
Add a ment  | 

1 Answer 1

Reset to default 6

use

student?.id

in unit test you have to provide value for student

beforeEach(() => {
  ...
  ponent.student = value;
  fixture.detectChanges();
);
Post a comment

comment list (0)

  1. No comments so far