How do I create a fake NgForm object in an Angular unit test?

Viewed 9073

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:

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

1 Answers
Related