Home > Mobile >  Cypress angular material select multiple: confirm if mat-option is checked
Cypress angular material select multiple: confirm if mat-option is checked

Time:08-05

I am trying to write a e2e test with Cypress for the following use case in an angular app:

there is this material select with the "multiple" configuration that is opened when a button is pressed:

<button  mat-button (click)="countriesDrop.open()" data-cy="countryBtn">
              
<p>{{ 'ADD' | translate }}</p>

<mat-select #countriesDrop style="width: 0;"  [formControl]="countriesForm" multiple data-cy="countryMatSelect">

    <!-- Select All -->
    <mat-option *ngIf="countryAssociationsOptions.length > 1" #allCountriesOption (click)="toggleAllCountryAssociation()" [value]="selectAllCountries" data-cy="countryAllOption">
        {{ 'SELECT_UNSELECT_ALL' | translate }}
    </mat-option>

    <!-- Country -->
    <mat-option (onSelectionChange)="onChangeCountryAssociation($event)" *ngFor="let country of countryAssociationsOptions" [value]="country" data-cy="countryMatOption">
        {{ country.name }}
    </mat-option>

</mat-select>
</button>

The objective is to test when there are 4/5 selected options and the fifth option is selected if after the click, the "checkbox" icon is marked as "checked" and if the "Select/Unselect All" option also got marked with a "checked".

Right now using the code below I can already open the mat-select, select my desired option and close it, but as mentioned above, I want to verify that the mat-pseudo-checkbox got checked.

cy.get('[data-cy=countryBtn]').click().wait(1000)
cy.get('[data-cy=countryMatOption]').contains('Venezuela').click().type('{esc}')

Is this possible with Cypress?

I tried to do it like this:

cy.get('[data-cy=countryBtn]').click().wait(1000)
cy.get('[data-cy=countryMatOption]').contains('Venezuela').click().should('be.checked')
cy.get('[data-cy=countryAllOption]').should('be.checked')

But it gives the following error:

expected '<span.mat-option-text>' to be 'checked'

enter image description here

Any ideas would be appreciated, thanks

Edit: Added html print with the selected option

CodePudding user response:

I see that a class called mat-checkbox-checked is added when the item is checked. So we will find the presence of this class after the element is checked.

cy.get('[data-cy=countryBtn]').should('be.visible').click()
cy.get('[data-cy=countryMatOption]')
  .contains('Venezuela')
  .then(($ele) => {
    cy.wrap($ele).click()
    cy.wrap($ele)
      .invoke('attr', 'class')
      .should('contain', 'mat-checkbox-checked')
  })
cy.get('[data-cy=countryAllOption]')
  .invoke('attr', 'class')
  .should('contain', 'mat-checkbox-checked')
  • Related