首页 > 解决方案 > Angular中测试用例的未定义​​属性错误

问题描述

测试用例失败并出现错误,指出未定义的属性。

我将roleID 传递给getResults()。当我为 ('它应该创建组件').truthy 运行 ng 测试时,它会抛出一个错误 --> 未定义的角色 ID。

我也在 HTML 中使用过 *ngIf="x?.roleID",我遇到了同样的错误。

文件示例*.spec.ts

// it('should create', () => {
//     expect(component).toBeTruthy();
//   });
// While running the ng Test for this Component, it is throwing error like ngOnit() Id of undefined property

标签: angularkarma-jasmine

解决方案


如果this.inputArray在您的组件中未定义,则ngOnInit在尝试访问该roleID属性时该方法将失败。在测试期间,您必须确保初始化您的输入,即inputArray正确的属性,这可以通过以下方式完成

a)将您的测试包装在充分设置输入的测试驱动程序组件中,例如通过使用如下模板:

<your-component [inputArray]="validArray"></your-component>

b)在准备测试时初始化您的组件属性:

beforeEach(() => {
  fixture = TestBed.createComponent(YourComponent);
  component = fixture.componentInstance;
  // assign valid array to property here:
  component.inputArray = [{roleID: 1, ...}];
  // ... your ngOnInit will be run now:
  fixture.detectChanges();
});

推荐阅读