angular - 单元测试 Angular 表单和 subFormGroup
问题描述
尝试在测试规范中构建表单时出错。表单构建函数还构建了一个子表单数组。寻找最好的方法来测试这个
组件.ts
buildForm() {
return this.peopleForm = this.fb.group({
people: this.fb.array([this.buildSubFormGroup()]),
effective_date: [this.firstOfNextMonth(), Validators.required]
});
}
buildSubFormGroup(type: string = 'primary') {
return this.fb.group({
type: [type],
first_name: ['', Validators.required],
last_name: ['', Validators.required],
dob: ['', Validators.required],
gender: ['', Validators.required],
uses_tobacco: ['', Validators.required],
affordable_care: ['', Validators.required],
is_pregnant: [''],
});
}
组件.spec.ts
it('should be able to build the peopleForm', () => {
component.buildForm();
fixture.detectChanges();
expect(component.peopleForm.controls['type'].value).not.toBeNull();
});
错误: 错误:没有 FormControl 实例附加到名称为“有效日期”的表单控件元素
解决方案
当您运行时detectChanges()
,组件被初始化。检查以下内容:
- 您是否在
beforeEach
函数之前运行it()
函数? - 为什么要退回作业?什么时候在您的组件中调用 buildForm 函数?比重新运行它更好地引起调用。
- 你的 HTML 是什么。尝试绑定
[FormControl]
而不是formControlName
单元测试的想法是引起调用相应函数的动作。
示例:
ngOnInit
当调用 detectChanges() 时。
onClickSomething
当您单击调用它的项目时,而不是通过调用 compoment.onClickSomething 函数。
您正在测试整个组件。
如需更多信息,请添加 html 和整个组件代码。
推荐阅读
- java - 有没有办法在一个 Talend Open Studio 项目中容纳多个文件而不会耗尽内存?
- java - Java - 为来自外部库的类定义一个通用接口
- python - 蟒龟 tr
- java - 使用客户端凭据授权从具有 Java HttpClient 的服务器检索访问令牌
- html - 自定义字体无法在 Wordpress 上的其他计算机上呈现
- python - 在 Visual Studio 中将目录添加到 PATH
- amazon-web-services - 在没有源文件夹名称的情况下将文件复制到 s3
- html - 将图像大小调整为父 div?仅使用父 div?
- c# - 使用 ssh.net.sftp 从 sftp 目录下载大量文件的有效方法?
- html - 未对齐的块对象