Selecting options from Mat-select using cypress

10,198

Solution 1

Opens up the mat-option dialog for the mat-select & selects the field that contains "Apple Inc."

cy.get('mat-select[formControlName=companyName]').click().get('mat-option').contains('Apple Inc.').click();

Solution 2

Basically what I did was to simulate the Dropdown opening and then sumulate another click for item selection:

// simulate click event on the drop down
cy.get('mat-select').first()
        .click(); // opens the drop down

// simulate click event on the drop down item (mat-option)
cy.get('.mat-option-text span')
  .contains('Your MatItem Text')
  .then(option => {
            option[0].click();  // this is jquery click() not cypress click()
        });

Solution 3

First, click on select for openning the overlay, then click on your option based on your option text content:

cy.get('mat-select[formcontrolname="departament"]').click();
cy.get('mat-option').contains('Lima').click();

My option text was Lima(+001). When I queried .contains('Lima') I got 'AssertionError'. But when I query .contains('Lima') or .contains('001') element is found. It's seems to me that only supports alphanumeric (I didn't go in deep).

Share:
10,198
PremKumar
Author by

PremKumar

Updated on June 19, 2022

Comments

  • PremKumar
    PremKumar almost 2 years

    I have Mat-select dropdown as follows

    <mat-form-field>
       <mat-label>Gender</mat-label>
          <mat-select id="gender" required formControlName="gender">
             <mat-option id="Male" value="male"> Male </mat-option>
             <mat-option value="female"> Female </mat-option>
          </mat-select>
     </mat-form-field>
    

    I'm trying to use Cypress to select male or female from the field.

    cy.get('mat-select').click().select('Male')
    

    With the above code I get the following error:

    CypressError: cy.select() can only be called on a <select>. Your subject is a: <mat-select>
    

    I need some help in fixing this, thank you.

    The code that worked for me.

    cy.get('#gender').click().then(() => {
                cy.get('#male').click()
            })
    
    • KiraAG
      KiraAG almost 5 years
      Did you check this answer?
  • Ian Jamieson
    Ian Jamieson almost 4 years
    Why are you using jQuery click and not Cypress?
  • Juri
    Juri over 2 years
    not working for me - message: can only be called on a <select>. Your subject is a: <mat-select...