如何在Angular单元测试中创建假的NgForm对象?

问题描述:

我有一个包含如下模板的组件:

I have a component with a template like the following:

// Template
<form #f="ngForm" (ngSubmit)="onFormSubmit(f)">
  <!-- A bunch of form fields -->
</form>

我的组件有如下方法:

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:

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()功能?我已经尝试过上面的操作并得到错误:此组尚未注册表单控件。如果您正在使用ngModel,您可能需要检查下一个tick(例如使用setTimeout)。

How can I create a mock version of the form to pass in to the onFormSubmit() function? 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 (e.g. use setTimeout)."

这应该可行

const testForm = <NgForm>{
    value: {
        name: "Hello",
        category: "World"
    }
};