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

元气小坏坏 提交于 2019-12-08 20:07:51

问题


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:


This should work

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


来源:https://stackoverflow.com/questions/45332847/how-do-i-create-a-fake-ngform-object-in-an-angular-unit-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!