如何在Angular单元测试中创建假的NgForm对象? [英] How do I create a fake NgForm object in an Angular unit test?

查看:73
本文介绍了如何在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"
    }
};

这篇关于如何在Angular单元测试中创建假的NgForm对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆