我有一个带有如下模板的组件:
// Template
<form #f="ngForm" (ngSubmit)="onFormSubmit(f)">
<!-- A bunch of form fields -->
</form>
我的组件有一个类似的方法:
onFormSubmit(form: NgForm) {
this.save();
}
我想编写一个基本上像这样的测试,测试提交表单时调用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');
});
如何创建表单的模拟版本以传递给
onFormSubmit()
函数?我尝试执行上述操作,但出现错误:"There are no form controls registered with this group yet. If you're using ngModel, you may want to check next tick (e.g. use setTimeout)."
最佳答案
这应该工作
const testForm = <NgForm>{
value: {
name: "Hello",
category: "World"
}
};
关于angular - 如何在Angular单元测试中创建伪造的NgForm对象?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45332847/