One of my components has a template structured as follows:
<form class="form-horizontal" #privateEmailForm="ngForm" (ngSubmit)="onSubmit()">
<div class="form-group">
<label class="col-md-4 control-label text-left" for="tiNewEmail" >Email</label>
<div class="col-md-8">
<input id="tiNewEmail" #tiNewEmail="ngModel" class="form-control input-md"
[(ngModel)]="newEmail" type="text" email required>
<span [shown]="tiNewEmail.invalid && (tiNewEmail.dirty || privateEmailForm.submitted)"></span>
</div>
</div>
<button type="submit" class="btn btn-red btn-lg" >Save</button>
</form>
I am now working on writing unit tests for this component, specifically to ensure that the email validation message appears after clicking the submit button even if the email input is still pristine. The challenge I faced was that in the unit test environment, all inputs and forms are considered valid by default. I didn't want to simulate events from the input element itself because that would make the input dirty. After some experimentation, I discovered that dispatching an event from the component's native element made empty required controls and the form invalid:
debugElement.nativeElement.dispatchEvent(new Event('mouseover'));
fixture.detectChanges();
While this approach worked for me, I'm curious if there is a more appropriate method to test the validity of untouched form controls?