0
上下文
我有一個基本形式(反應形式)的組件。我嘗試在此表單上測試提交事件,看它是否正確調用了必要的方法。角度測試提交事件的反應形式
我的問題
我不能觸發提交表單的事件
文件
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);
那麼,如何觸發表單提交的事件嗎?
謝謝,它的工作原理。我導入了ReactiveFormsModule和FormsModule以避免出現ControlContainer錯誤。 – BlackHoleGalaxy
任何想法爲什麼觸發我的提交按鈕沒有開箱即用? – BlackHoleGalaxy
它不起作用,因爲沒有提交事件的處理程序,因爲沒有將處理它的指令,因爲您沒有導入包含此指令的ReactiveFormsModule – yurzui