1

I have a component with template like this:

<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>

Now I have to write unit test on this component, which will check that email validation message appears after submit button click even if email input pristine. The problem is that in unit test, all inputs and form are valid by default. I don't want to dispatch events from input like suggested here https://stackoverflow.com/a/39918775/360171 because I need to keep input control pristine. I found that if I dispatch any event from component's native element, empty required controls and form become invalid:

debugElement.nativeElement.dispatchEvent(new Event('mouseover')); 
fixture.detectChanges();

At least, it works for me, but I'm not sure, is there a more correct way to test untouched form controls validity?

Community
  • 1
  • 1
Yuriy Rozhovetskiy
  • 22,270
  • 4
  • 37
  • 68

1 Answers1

0

You should assign an empty value first and then you should check if the required error message is displayed or not.

debugElement.query(ByCss('#tiNewEmail')).nativeElement.value = ''

and you should check if the error message is applied as

expect(debugElement.query(ByCss('#tiNewEmail > span')).nativeElement.innerHTML).toBe('Required')
Aravind
  • 40,391
  • 16
  • 91
  • 110