I have a problem in clicking in a select element using cypress. This is the element to click:
And i receive this error.
cy.click()
cannot be called on a <select>
element. Use the cy.select()
command instead to change the value.
This is my code:
cy.get('[name^=shopveg]').click()
After searching some people advise using the trigger command. Changed the code to:
cy.get('[name^=shopveg]').trigger('click')
The step pass in the cypress execution but the click was not executed.
CodePudding user response:
As the message says, .select()
is the command to use
cy.get('[name^=shopveg]').select('Bananas')
That's because <select>
behavior is implemented by a web component (see slot
tag), not javascript, so there's no click handler available.
CodePudding user response:
To validate the values in the select menu, you can iterate through them with cy.each()
.
const options = [ "Batatas", "Arroz", "Bananas", "Tomates", "Macaz" ];
cy.get('[name^=shopveg]').find('option').each(($el, index) => {
cy.wrap($el).should('have.text', options[index]);
});
As @Grainger answered, you can then use cy.select()
to pick a value.
CodePudding user response:
Given the select looks like a "special" implementation, i.e a web component with slots, you may need to click it open to see the option values (lazy loading).
If so, try with cypress-real-events plugin
Install
npm install cypress-real-events
// or
yarn add cypress-real-events
In /cypress/suport/e2e.js
import "cypress-real-events";
Test
cy.get('[name^=shopveg]')
.should('have.value', '1') // confirm initial value
.realClick() // click open
cy.contains('option', 'Batatas') // this option exists
cy.contains('option', 'Arroz') // this option exists
cy.contains('option', 'Bananas') // this option exists
// etc
cy.get('[name^=shopveg]')
.select('Bananas') // select new option
.should('have.value', '3') // confirm new value