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

时间:2017-07-26 16:39:00

标签: angular unit-testing jasmine

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

// 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)."

1 个答案:

答案 0 :(得分:11)

这应该有效

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