角度测试提交事件的反应形式
问题描述:
上下文
我有一个基本形式(反应形式)的组件。我尝试在此表单上测试提交事件,看它是否正确调用了必要的方法。角度测试提交事件的反应形式
我的问题
我不能触发提交表单的事件
文件
Component.html
<form class="form-horizontal"
id="staticForm"
[formGroup]="mySimpleForm"
(ngSubmit)="sendMethod();"
>
<input type="text" formGroupName="email">
<button type="submit">Send form</button>
</form>
Component.ts
ngOnInit() {
this.initSimpleForm();
}
private initSimpleForm() {
let file = null;
this.mySimpleForm = this.formBuilder.group({
email: [
'',
[
Validators.required
]
]
});
}
sendMethod() {
console.log('submitted');
}
component.spec.ts
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('[email protected]');
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
});
我也试过了,而不是在形式调用submit
:
fixture.debugElement.query(By.css('button')).triggerEventHandler('click', null);
那么,如何触发表单提交的事件吗?
答
第一种方案是直接调用ngSubmit
:
.triggerEventHandler('ngSubmit', null);
第二个选项是进口ReactiveFormsModule
将在内部设置形式submit
处理程序。所以你的触发方法应该工作:
TestBed.configureTestingModule({
declarations: [
MyComponent
],
imports: [ReactiveFormsModule], // <== import it
providers: []
谢谢,它的工作原理。我导入了ReactiveFormsModule和FormsModule以避免出现ControlContainer错误。 – BlackHoleGalaxy
任何想法为什么触发我的提交按钮没有开箱即用? – BlackHoleGalaxy
它不起作用,因为没有提交事件的处理程序,因为没有将处理它的指令,因为您没有导入包含此指令的ReactiveFormsModule – yurzui