Scenario
In my component, I have a basic form implemented using reactive forms in Angular. My objective is to test the submission event of this form to ensure that the appropriate method is executed.
The Issue at Hand
I am encountering challenges in triggering the submit event of the form.
Code Snippets
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('<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b2c6d7c1c6f2c6d7c1c69cd1dddf">[email protected]</a>');
fixture.debugElement.query(By.css('form')).triggerEventHandler('submit', null);
fixture.detectChanges();
expect(console.log).toHaveBeenCalled(); // FAILS
});
// TO ensure that my spy on console log functions correctly, I performed this test and it passed
it(`will notify on direct sendMethod Call`, () => {
spyOn(console, 'log');
comp.sendMethod();
fixture.detectChanges();
expect(console.log).toHaveBeenCalled(); // SUCCESS
});
I have also attempted to trigger the form submission by calling click
on the button instead:
fixture.debugElement.query(By.css('button')).triggerEventHandler('click', null);
Is there a workaround to successfully trigger the form submit event?