【发布时间】: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