[英]Angular testing submit event on reactive form
I have a component with a basic form (reactive form). 我有一个基本形式的组件(反应形式)。 I try to test the submit event on this form to see if it calls the necessary method properly.
我尝试在此表单上测试提交事件,看它是否正确调用了必要的方法。
I can't trigger the submit event of the form 我无法触发表单的提交事件
<form class="form-horizontal"
id="staticForm"
[formGroup]="mySimpleForm"
(ngSubmit)="sendMethod();"
>
<input type="text" formGroupName="email">
<button type="submit">Send form</button>
</form>
ngOnInit() {
this.initSimpleForm();
}
private initSimpleForm() {
let file = null;
this.mySimpleForm = this.formBuilder.group({
email: [
'',
[
Validators.required
]
]
});
}
sendMethod() {
console.log('submitted');
}
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
MyComponent
],
imports: [],
providers: [
FormBuilder
],
schemas: [NO_ERRORS_SCHEMA]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
comp = fixture.componentInstance;
});
it(`should notify in console on form submit`, () => {
spyOn(console, 'log');
comp.mySimpleForm.controls['email'].setValue('test@test.com');
fixture.debugElement.query(By.css('form')).triggerEventHandler('submit', null);
fixture.detectChanges();
expect(console.log).toHaveBeenCalled(); // FAILS
});
// TO make sure my spy on console log works, I made this and it works
it(`will notify on direct sendMethod Call`, () => {
spyOn(console, 'log');
comp.sendMethod();
fixture.detectChanges();
expect(console.log).toHaveBeenCalled(); // SUCCESS
});
I also tried that instead of calling submit
on form: 我也尝试过而不是在表单上调用
submit
:
fixture.debugElement.query(By.css('button')).triggerEventHandler('click', null);
How then to trigger the form submit event? 然后如何触发表单提交事件?
First option is calling ngSubmit
directly: 第一个选项是直接调用
ngSubmit
:
.triggerEventHandler('ngSubmit', null);
Second option is importing ReactiveFormsModule
that will internally set submit
handler on form. 第二个选项是导入
ReactiveFormsModule
,它将在表单内部设置submit
处理程序。 So your trigger method should work: 所以你的触发方法应该工作:
TestBed.configureTestingModule({
declarations: [
MyComponent
],
imports: [ReactiveFormsModule], // <== import it
providers: []
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.