angular - 如何在 Angular 单元测试中创建伪造的 NgForm 对象?

标签 angular unit-testing jasmine

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

// 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() 函数?我已尝试执行上述操作,但出现错误:“尚未向该组注册任何表单控件。如果您使用的是 ngModel,则可能需要检查下一个勾号(例如使用 setTimeout)。”

最佳答案

这应该可行

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

关于angular - 如何在 Angular 单元测试中创建伪造的 NgForm 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45332847/

相关文章:

angular - 在 Angular 4 中更改事件的按钮类

Angular2 keyup事件更新ngModel光标位置跳转到结束

javascript - 使用无效数据调用 DocumentReference.set()。不支持的字段值 : undefined (found in field uid)

java - Mockito 转换为泛型

html - 如何在其子组件-Angular 2 中覆盖根组件的 css 类?

c# - 如何在 .NET 中测试可执行文件

javascript - 如何使用 JavaScriptCore 框架执行 JavaScript?

javascript - 如何正确使用createSpyObj

javascript - AngularJS 中的单元测试 - 模拟服务和 promise

c# - 基本 RX TestScheduler 时序