angular - 角度测试无法读取未定义的属性“名称”
问题描述
我有一个 ModalComponent,它通过 @Input 接受来自父级的一些属性。
这会导致测试问题
TypeError:无法读取未定义的属性“名称”
名称在 ngOnInit 中使用,应该来自@Input displayeddata
.
如何在单元测试中通过它?
目前我的测试看起来如此
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ModalComponent, FilterComponent],
imports: [ReactiveFormsModule, TranslateModule]
})
.compileComponents();
}));
beforeEach(async () => {
fixture = TestBed.createComponent(ModalComponent);
component = fixture.componentInstance;
component.displayeddata = {
name: 'One component',
caption: 'Caption',
componentName: 'TextareaComponent'
};
fixture.detectChanges();
});
it('should create', async () => {
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(component).toBeTruthy();
});
});
这是对我的组件的一项测试,但失败了。
更新#1
这是我得到的console.log(this.displayeddata);
Object
caption: "Caption"
component: "TextareaComponent"
name: "One component"
我还稍微更改了我的代码(更新的代码),现在出现了一个新错误TypeError: Cannot read property 'caption' of undefined
更新#2
modal.component.ts
export class ModalComponent implements OnInit {
@Input() showenpunctsnow;
@Input() displayeddata;
@Output() ComponentParametrsInputs: FormGroup = this.fb.group({
name: ['', Validators.required],
caption: ['', Validators.required],
component: ['']
});
constructor(private fb: FormBuilder) {}
ngOnInit() {
console.log(this.displayeddata);
this.ComponentParametrsInputs = this.fb.group({
name: [this.displayeddata.name, Validators.required],
caption: [this.displayeddata.caption, Validators.required],
component: [this.displayeddata.componentName]
});
}
解决方案
只是在这里发表评论,即使这已经解决,以防其他人遇到同样的问题。
问题很可能来自 html 文件,而不是单元测试或组件本身。
在您的 html 文件中:
- 转到您正在使用的地方
{variable}.name
- 在相应的部分、div 或以其他方式添加
*ngIf="{variable}"
这应该首先检查这个变量是否存在。然后在您的单元测试中,只需执行以下操作:
it('should create', ()=> {
expect(component).toBeTruthy();
}
如果你想然后检查组件是否会加载指定的name
:
it('should create with specified name', () => {
component.{variable}.name = 'Foo'
fixture.detectChanges();
expect(fixture.debugElement.nativeElement.innerHTML)
.toContain(component.{variable}.name)
}
推荐阅读
- angular - 我怎样才能使我的第二个块在链触发器中?
- javascript - 增加延迟加载检测的视口
- reactjs - 带有 IE11 polyfill 导入的 Starter create-react-app 仍然在 IE11 中中止
- javascript - 如何将 HTML 文本框输入传递给 Javascript 变量
- angular - 类型上不存在属性
- html - 如何获取域下所有可访问 url 的列表?
- windows - CMD 给我错误“系统找不到文件 output.txt”
- android - 如何从基于 Unity 的应用程序获取数据到第三方 Android 应用程序?
- time-complexity - 计算 big-O 时如何处理本机函数的时间复杂度
- angular - 无法解析 APIService 的所有参数