首页 > 解决方案 > Jasmine 单元测试:如何访问由 @input() 设置的属性?使用 component.propertyname 访问它会返回 undefined

问题描述

ts文件:

@input() selectedDep: WebMessagingDeployments[]

规格文件:

beforeEach(() => {

    fixture = TestBed.createComponent(DeploymentAssignmentFormComponent);
    component = fixture.componentInstance;
    
    console.log(component.selectedDep) // returns undefined
    component.selectedDep.push(mockDepData); //this line throws error. TypeError: Cannot read property '0' of undefined
}));  

标签: angularkarma-jasmine

解决方案


看起来您尚未selectedDep在组件或测试文件中初始化。

几个选项是:

  1. 声明时初始化

    @Input() selectedDep: WebMessagingDeployments[] = [];

  2. 在测试中初始化

    夹具 = TestBed.createComponent(DeploymentAssignmentFormComponent); 组件=fixture.componentInstance;component.selectedDep = [/* 这里的值 */]; 夹具.detectChanges();


推荐阅读