angular - 类型错误 : Cannot read properties of undefined (reading '<myvariable>' )

标签 angular unit-testing jasmine karma-jasmine

在其中一个组件中运行 ng 测试时,我遇到了以下错误。

TypeError: Cannot read properties of undefined (reading 'dateOfLeaving')
error properties: Object({ ngDebugContext: DebugContext_({ view: Object({ def: Object({ factory: Function, nodeFlags: 33669121, rootNodeFlags: 33554433, nodeMatchedQueries: 0, flags: 0, nodes: [ Object({ nodeIndex: 0, parent: null, renderParent: null, bindingIndex: 0, outputIndex: 0, checkIndex: 0, flags: 33554433, childFlags: 114688, directChildFlags: 114688, childMatchedQueries: 0, matchedQueries: Object({  }), matchedQueryIds: 0, references: Object({  }), ngContentIndex: null, childCount: 1, bindings: [  ], bindingFlags: 0, outputs: [  ], element: Object({ ns: '', name: 'app-view-employee', attrs: [  ], template: null, componentProvider: Object({ nodeIndex: 1, parent: <circular reference: Object>, renderParent: <circular reference: Object>, bindingIndex: 0, outputIndex: 0, checkIndex: 1, flags: 114688, childFlags: 0, directChildFlags: 0, childMatchedQueries: 0, matchedQueries: Object, matchedQueryIds: 0, references: Object, ngContentIndex: -1, childCount: 0, bindings: Array, bindingFlags: 0, outputs ...
TypeError: Cannot read properties of undefined (reading 'dateOfLeaving')
    at ViewEmployeeComponent.ngOnInit (http://localhost:9876/_karma_webpack_/webpack:/src/app/employee/view/view-employee/view-employee.component.ts:22:17)
    at checkAndUpdateDirectiveInline (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.js:24503:1)
    at checkAndUpdateNodeInline (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.js:35163:1)
    at checkAndUpdateNode (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.js:35102:1)
    at debugCheckAndUpdateNode (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.js:36124:36)
    at debugCheckDirectivesFn (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.js:36067:1)
    at Object.eval [as updateDirectives] (ng:///DynamicTestModule/ViewEmployeeComponent_Host.ngfactory.js:10:5)
    at Object.debugUpdateDirectives [as updateDirectives] (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.js:36055:1)
    at checkAndUpdateView (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.js:35067:1)
    at callWithDebugContext (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.js:36407:1)

employee.ts

export class Employee
{

    
    id:number;
    name:string;
    dateOfBirth:string;
    designation:string;
    dateOfJoining:string;
    workLocation:string;
    email:string;
    contactNo:number;
    dateOfLeaving:string

    constructor(){}
    
    static getEmployee(id:number,
        name:string,
        dob:string,
        designation:string,
        dateOfJoining:string,
        workLocation:string,
        email:string,
        contactNo:number,
        dateOfLeaving:string
    ) :Employee
    {
        let emp = new Employee();
        emp.id = id;
        emp.name = name;
        emp.dateOfBirth = dob;
        emp.designation =designation;
        emp.dateOfJoining = dateOfJoining;
        emp.workLocation = workLocation;
        emp.email = email;
        emp.contactNo =contactNo;
        emp.dateOfLeaving = dateOfLeaving
        return emp;
    }

} 

view-component.ts

import { Component, OnInit } from '@angular/core';
import { CommonService } from 'src/app/service/common.service';
import { Employee } from '../../employee';
import { EmployeeService } from '../../employee.service';

@Component({
  selector: 'app-view-employee',
  templateUrl: './view-employee.component.html',
  styleUrls: ['./view-employee.component.css']
})
export class ViewEmployeeComponent implements OnInit {

  constructor(private employeeService: EmployeeService, private genericServices: CommonService) { }

  emp:Employee; 
  availableLocations: string[] = [];
  msg:string;

  ngOnInit() 
  {
    this.emp = this.employeeService.selectedEmployee;
    if(this.emp.dateOfLeaving == null)
    {
      this.emp.dateOfLeaving = '';
    }
    this.genericServices.getWorkLocations().subscribe(
    
      (resp:string[]) =>
      {
        this.availableLocations = this.availableLocations.concat( resp);
      },
      (err: any) => 
      {
        console.log("err" + err)
      }

    );
  }


  saveEmployee()
  {
    this.employeeService.updateEmployee(this.emp).subscribe(
      (resp) =>
      {
        if(resp['status'] ==200)
        {
          let existingEmpIndex = this.employeeService.employees.findIndex((exitsEmp) =>  this.emp.id == exitsEmp.id);
          this.employeeService.employees[existingEmpIndex] = this.emp;
          this.msg = resp['message'];
        }
      },
      (errMsg) =>
      {
        this.msg = errMsg['error']['errorMessage'];
      }
    )
  }
}

查看-employee.component.spec.ts

import { HttpClientModule } from '@angular/common/http';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { FormsModule } from '@angular/forms';
import { CommonService } from 'src/app/service/common.service';
import { Employee } from '../../employee';
import { EmployeeService } from '../../employee.service';

import { ViewEmployeeComponent } from './view-employee.component';

describe('ViewEmployeeComponent', () => {
  let component: ViewEmployeeComponent;
  let fixture: ComponentFixture<ViewEmployeeComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ ViewEmployeeComponent ],
      imports: [FormsModule, HttpClientModule],
      providers: [EmployeeService, CommonService]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ViewEmployeeComponent);
    component = fixture.debugElement.componentInstance;
    component.emp = new Employee();
    component.emp.id =1;
    component.emp.dateOfLeaving ="Today";
    fixture.detectChanges();
  });

  it('should create', () => {
    fixture.whenStable().then( ()=> {
      fixture.detectChanges();
      
      // expect(component).toBeTruthy();
    })
  });
});

员工服务.ts

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { env } from 'process';
import { environment } from 'src/environments/environment';
import { URLMapping } from '../shared/URLMapping';
import { Employee } from './employee';

@Injectable({
  providedIn: 'root'
})
export class EmployeeService {
  

  employees:Array<Employee> =[];
  selectedEmployee:Employee;

  constructor(private httpClient: HttpClient)
  { }

  fetchEmployee(emp:Employee)
  {
    console.log(emp)
    // return this.httpClient.post(environment.applicationURL + URLMapping.EMPLOYEE_VIEW, emp);
    return this.selectedEmployee = emp;
    
  }

  createEmployee(emp:Employee)
  {
    return this.httpClient.post(environment.applicationURL + URLMapping.EMPLOYEE_ADD, emp);
  }

  getEmployees()
  {
    
    return this.httpClient.post(environment.applicationURL + URLMapping.EMPLOYEE_LIST, {});
  }

  updateEmployee(emp:Employee)
  {
    return this.httpClient.post(environment.applicationURL + URLMapping.EMPLOYEE_SAVE, emp);
  }

  deleteEmployee(employees: Employee[]) {
    return this.httpClient.post(environment.applicationURL + URLMapping.EMPLOYEE_DELETE, employees);
    
  }
}

id 属性也面临同样的问题。非常感谢任何引用或解决方案。

最佳答案

这里的问题是,只有当您调用 fixture.detectChanges() 并且您正在 ngOnInit() 中初始化 emp 对象时,才会调用 Angular 生命周期方法。因此在调用 fixture.detectChanges()

之前您无法访问 emp 对象属性

尝试下面的代码(view-employee.component.spec.ts):

 beforeEach(() => {
    fixture = TestBed.createComponent(ViewEmployeeComponent);
    fixture.detectChanges();
    component = fixture.debugElement.componentInstance;
    component.emp = new Employee();
    component.emp.id =1;
    component.emp.dateOfLeaving ="Today";
  });

我还假设 this.employeeService.selectedEmployee 至少会返回空对象,否则您还必须模拟 EmployeeService

服务-

...
export class EmployeeService {
  employees:Array<Employee> =[];
  selectedEmployee:Employee = <Employee>{};
...

关于angular - 类型错误 : Cannot read properties of undefined (reading '<myvariable>' ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69303457/

相关文章:

angular - 如何使用 ng2-file-upload 返回响应

angular - 如何在 Angular 中匹配 toHaveBeenCalledWith 中的部分 url

selenium-webdriver - 类型错误 : WebElementCondition did not resolve to a WebElement: [object Object]

angularjs - Promise 在 AngularJS Jasmine 测试中解决得太晚了

javascript - 使用 Jest 模拟在 vue 组件中导入的模块

javascript - 为什么需要使用 jasmine 的 runs 和 waitFor 函数?

css - 如何将 css 根常量共享到另一个 css 文件?

typescript - SyntaxError : node_modules/angular2/ts/package. json: 意外的标记 <

angularjs - 如何在 MVC6 项目中安装 Angular2?

reactjs - enzyme /Jest 上下文 API 注入(inject)( react )不起作用