[英]testing angular template driven forms
I am using angular 5, always the .controls
property of the form is empty. 我正在使用角度5,窗体的
.controls
属性始终为空。 Not sure why during testing angular doesn't create the form controls by reading the template file. 不确定为什么在测试期间angular不会通过读取模板文件来创建表单控件。
Template file 模板文件
<form
#myForm="ngForm"
novalidate>
<input
#myCtrl
required
type="input"
name="myCtrl"
id="myCtrl"
[(ngModel)]="value">
</form>
Component file 组件文件
@ViewChild('myForm') myForm: NgForm;
In my tests, when I console.log the following, I get {}
在测试中,当我console.log以下内容时,我得到
{}
fixture.debugElement.componentInstance.myForm.controls
The form also has errors: null
and status VALID
despite the fact that the form should contain an invalid FormControl
. 表单也有错误:尽管表单应包含无效的
FormControl
,但VALID
null
和status VALID
。 Is it possible to unit test forms when they are configured with ViewChild
rather than FormBuilder
? 使用
ViewChild
而不是FormBuilder
配置表单时,是否可以对表单进行单元测试? Is there a way to do it with my ViewChild
setup? 有没有一种方法可以使用
ViewChild
设置?
or do we have to mock the form by creating the controls again using FormGroup and assign it to 还是我们必须通过使用FormGroup再次创建控件来模拟表单并将其分配给
componentInstance.myForm.controls
? componentInstance.myForm.controls
吗?
I was missing async in beforeEach()
, though I had the testbed
configuration in async
. 尽管在
async
有testbed
配置,但我在beforeEach()
中缺少async
。
Also use @ViewChild('nameOfForm') sampleForm: NgForm
; 也可以使用
@ViewChild('nameOfForm') sampleForm: NgForm
;
while the test runs the spec, the form controls specified in the template does gets initialized and available in component.sampleForm
当测试运行规范时,模板中指定的表单控件确实会初始化并在
component.sampleForm
可用
我认为您需要在检查控件之前放入Fixture.detectChanges()。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.