0

I can get the input value of the form field above by using this query in my spec file:

expect(findEl(fixture, "mail").nativeElement.value).toBe('email@mail.com');
<mat-form-field fxFlex="auto">
  <mat-label>E-Mail</mat-label>
     <input
       matInput
       required
       type="email"
       readonly
       autocomplete="off"
       data-testid="mail"
       formControlName="mail"
     />
     <mat-icon
       matSuffix
       mat-icon-button
       >email</mat-icon
     >
</mat-form-field>

But when I try to do the same within a mat-select form field, value returns undefined

<mat-form-field fxFlex="auto">
  <mat-label>Sexo</mat-label>
  <mat-select
    required
    data-testid="genderType"
    formControlName="genderType"
  >
    <mat-option>--</mat-option>
    <mat-option *ngFor="let gender of genders" [value]="gender.id">
      {{ gender.name }}
    </mat-option>
  </mat-select>
  <mat-icon
    matSuffix
    mat-icon-button
    >wc</mat-icon
  >
</mat-form-field>
expect(findEl(fixture, "genderType").nativeElement.value).toBe(1);

//Error: Expected undefined to be 1.

How can I get the selected value or text of a mat-select?

Bianca Yameê
  • 80
  • 1
  • 6

1 Answers1

0

You can probably use the other API similar to the input way with matInput directive but this time use matNativeControl.

<select matNativeControl formControlName="genderType" data-testid="genderType">
    <option>--</option>
    <option *ngFor="let gender of genders" [value]="gender.id">
      {{ gender.name }}
    </option>
  </select>

And then maybe expect(findEl(fixture, "genderType").nativeElement.value).toBe(1); will work.

All of those changes for a test may be too much.

I would do the following:

expect(component.form.get('genderType').value).toBe(1);

We test that the model on the form is correct and we will assume that mat-select will do its job correctly.

I don't have much experience with Angular Material, I found out about changing mat-select to select with matNativeControl directive from the documentation.

AliF50
  • 16,947
  • 1
  • 21
  • 37