'Selecting options from Mat-select using cypress
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()
})
Solution 1:[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:[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:[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).
Solution 4:[4]
Just for other people still strugling with this/similar issue, even after trying the solutions presented here.
Your problem might also be that you are using a within
block. Therefore mat-select
items cannot be reached after clicking on the mat-option
. So either take this part out of the within
block or use the {withinSubject:null}
option when getting the mat-select
item.
cy.get("mat-select[formControlName*='language']").click();
cy.get('mat-option', {withinSubject:null}).contains('English').click();
Solution 5:[5]
First,Select for opening the overlay, then select your option based on your option text content & use should()
to verify that selecting the exact option:
cy.get('mat-select').select('Male').should('have.value','male');
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Max |
Solution 2 | Mohammad Nakhaie |
Solution 3 | Daniel Delgado |
Solution 4 | PhilipAllStar |
Solution 5 | GHULAM NABI |