TypeError:无法读取未定义的属性'id'-Angular 8 Testing

时间:2019-07-30 05:44:11

标签: javascript angular unit-testing

我遇到TypeError:尝试在我的angular 8应用程序中执行单元测试时,无法读取未定义的属性'id'。

这是我的模板

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

这是我的组成部分

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

这是单元测试

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

1 个答案:

答案 0 :(得分:2)

使用

student?.id

在单元测试中,您必须为意外事件提供价值

beforeEach(() => {
  ...
  component.student = value;
  fixture.detectChanges();
);