angular - 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
解决方案
如果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();
});
推荐阅读
- python - Python:根据内容组合 Pandas 行
- asp.net-core - ionic httpclient 在带有 net core 0 Unknown Error 的模拟器上不起作用”
- python - 交叉熵上升而 AUC 上升(pytorch)
- sas - symputx 不允许我使用相同的宏函数存储不同的宏变量
- r - 如何使用 hunspell(或其他软件包)使用我自己的“字典”来纠正单词?
- r - Convert custom data type &/ calculating duration in R
- java - How to get JNDI datasource in Spring Boot from IBM WebSphere 9
- php - 如何根据类别在我的 single.php(wordpress)页面中显示 php 代码?
- apache-spark - 小型数据集的最佳(低延迟)火花设置
- jekyll - 在 GitHub 页面上找不到资源 Jekyll 博客