2017-07-26 46 views
2

我有喜欢的模板组件如下:如何在Angular单元测试中创建一个伪造的NgForm对象?

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

+0

_onFormSubmit_不使用*形式*参数。你的代码是否正确? –

+0

你能否更好的解释一下这个测试的实际目标是什么?我会测试,当调用onSubmit函数时,你的组件实际上会调用save()函数,或者甚至更好,我会检查我正在使用的服务是否实际尝试保存数据。 – pinkfloyd

+0

我已经更新了代码,以澄清它在做什么。 – Stewart

回答

3

这应该工作

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

为什么我没有想到这个? :) – Stewart

相关问题