I've an Angular component which has form validation. I'm unit testing to make sure it displays an error message if the input is invalid.
But when I try to change the <input>
box value, the control's state remains untouched
and the error doesn't display.
Here's the code:
<form #zipForm="ngForm">
<label>
<input type="text" id="postalCode" [(ngModel)]="postalCode" #postalCodeElem="ngModel" name="postalCode" [pattern]="validationPattern" required>
<button type="button" (click)="click(postalCodeElem.value)">Enroll</button>
<div *ngIf="postalCodeElem.invalid && postalCodeElem.touched">
<span id="required-postal-code" *ngIf="postalCodeElem?.errors?.required">
zip/postal code is required
</span>
<span id="invalidPostalCode" *ngIf="postalCodeElem?.errors?.pattern">
zip postal code is invalid
</span>
</div>
</label>
</form>
Test file:
it('should show error in case of invalid postal code', () => {
const elem: HTMLElement = fixture.nativeElement;
const inputElem: HTMLInputElement = elem.querySelector('input');
inputElem.value = 'L5L2';
inputElem.dispatchEvent(new Event('input', { bubbles: true }));
fixture.detectChanges();
const invalidErrorElem: any = elem.querySelector('span');
console.log('elem', elem);
console.log('invalidErrorElem', invalidErrorElem);
expect(invalidErrorElem).not.toBeNull();
});
I've created a stackblitz to demo the issue: https://stackblitz.com/edit/angular-testing-45zwkn?file=app%2Fapp.component.spec.ts
Any idea what am I doing wrong?
Aucun commentaire:
Enregistrer un commentaire