【问题标题】:How do I create a fake NgForm object in an Angular unit test?如何在 Angular 单元测试中创建假 NgForm 对象?
【发布时间】:2017-07-26 16:39:00
【问题描述】:

我有一个带有如下模板的组件:

// Template
<form #f="ngForm" (ngSubmit)="onFormSubmit(f)">
  <!-- A bunch of form fields -->
</form>

我的组件有一个类似的方法:

onFormSubmit(form: NgForm) {
  this.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 参数。你的代码正确吗?
  • 您能否更好地解释一下这个测试的实际目标是什么?我会测试当调用 onSubmit 函数时,你的组件实际上会调用 save() 函数,或者更好的是我会检查我正在使用的服务是否真的试图保存数据。
  • 我已经更新了代码以阐明它在做什么。

标签: angular unit-testing jasmine


【解决方案1】:

这应该可行

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

【讨论】:

  • 我怎么没想到呢? :)
  • 当我这样做时,我的测试表明 NgForm 对象上不存在方法“resetForm”。你如何模拟对 NgForm 对象方法的访问?
  • component.loginForm = {form: {}} as NgForm
猜你喜欢
  • 1970-01-01
  • 2017-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-07
  • 2010-12-16
  • 1970-01-01
相关资源
最近更新 更多