简体   繁体   中英

How to click in a select element with several options with Cypress?

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.

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.

Given the select looks like a "special" implementation, ie 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 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM