How to check for the presence of a `mat-error` element in unit tests?

80 views Asked by At

I'm writing unit tests for a form and I'm having problems checking for the presence of mat-errors. I looked it up and found some answered questions( 1 2 3 ) which I tried to incorporate with no success.

Here's part of the html I'm trying to test:

<form class="signin-form" [formGroup]="form">

    <mat-form-field class="">
      <mat-label>Email</mat-label>
      <input matInput type="email" placeholder="Email" formControlName="email">
      <mat-error test-id="error-email-empty" *ngIf="form.get('email')!.hasError('required')">
        An email is required
      </mat-error>
      <mat-error test-id="error-email-invalid" *ngIf="form.get('email')!.hasError('email')">
        The email provided is invalid
      </mat-error>
    </mat-form-field>
    ...
</form>

Here's the current state of the test:

describe('email is empty', () => {
  beforeEach(async () => {
    setEmail('')
    setPassword('Test1234')
    setPasswordConfirmation('Test1234')

    //markFormAsTouched()
    fixture.detectChanges()
    //await fixture.whenStable()

  })

  it('shows empty email error message', () => {
    //expect(matErrors()).toHaveLength(1)
    expect(errorEmailEmtpy()).not.toBeNull()
  })
})
...
function markFormAsTouched() {
  return component.form.markAsTouched()
}

function matErrors() {
  return page.querySelectorAll('mat-error')
}

function errorEmailEmtpy() {
  return page.querySelector('[test-id="error-email-emtpy"]')
}

A summary of what I tried:

  • Tried to get the element via test-id, which returned null
  • Tried to get all mat-error elements, which returned an empty array
  • Marked form as touched
  • Awaited for fixture.whenStable() with describe as async
  • Mixed and matched all of the above

But no success. Any suggestions are appreciated.

0

There are 0 answers