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

12

我有一个组件,其模板如下所示:

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

onFormSubmit 不使用 form 参数。你的代码正确吗? - Aleksandr Petrovskij
请问您能否更好地解释一下这个测试的实际目标是什么?我想测试当onSubmit函数被调用时,您的组件是否真正调用了save()函数,或者更好的是,我想检查我使用的服务是否尝试保存数据。 - pinkfloyd
我已经更新了代码以澄清它正在做什么。 - Stewart
1个回答

25

这应该能够工作

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

为什么我没想到呢? :) - Stewart
当我这样做时,我的测试显示NgForm对象上不存在'resetForm'方法。你如何模拟访问NgForm对象的方法? - djangofan
component.loginForm = {form: {}} as NgForm组件.登录表单 = {表单: {}} as NgForm - danday74

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接