[英]How do I create a fake NgForm object in an Angular unit test?
I have a component with a template like the following: 我有一个包含如下模板的组件:
// Template
<form #f="ngForm" (ngSubmit)="onFormSubmit(f)">
<!-- A bunch of form fields -->
</form>
My component has a method like: 我的组件有一个方法,如:
onFormSubmit(form: NgForm) {
this.save();
}
I want to write a test that basically looks like this, testing that the save function gets called when the form is submitted: 我想编写一个基本上看起来像这样的测试,测试在提交表单时调用save函数:
it('saves the widget when the form is submitted', () => {
let testForm = new NgForm([], []);
testForm.setValue({
name: "Hello",
category: "World"
});
component.onFormSubmit(testForm);
// Run tests to check that the component data was updated
expect(component.data.name).toEqual('Hello');
expect(component.data.category).toEqual('World');
});
How can I create a mock version of the form to pass in to the onFormSubmit()
function? 如何创建表单的模拟版本以传递给
onFormSubmit()
函数? I have tried doing the above and I get the error: "There are no form controls registered with this group yet. If you're using ngModel, you may want to check next tick (eg use setTimeout)."
我已经尝试过上面的操作并得到错误:
"There are no form controls registered with this group yet. If you're using ngModel, you may want to check next tick (eg use setTimeout)."
This should work 这应该工作
const testForm = <NgForm>{
value: {
name: "Hello",
category: "World"
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.