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('[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
});
I also tried that instead of calling submit
on form:
fixture.debugElement.query(By.css('button')).triggerEventHandler('click', null);
How then to trigger the form submit event?
First option is calling ngSubmit
directly:
.triggerEventHandler('ngSubmit', null);
Second option is importing ReactiveFormsModule
that will internally set submit
handler on form. So your trigger method should work:
TestBed.configureTestingModule({
declarations: [
MyComponent
],
imports: [ReactiveFormsModule], // <== import it
providers: []
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With