0
0
CypressHow-ToBeginner ยท 4 min read

How to Select Dropdown in Cypress: Simple Guide

To select a dropdown option in Cypress, use the cy.get() command to find the <select> element, then call .select() with the option's value, text, or index. For example, cy.get('select').select('Option1') selects the option named 'Option1'.
๐Ÿ“

Syntax

The basic syntax to select a dropdown option in Cypress is:

  • cy.get(selector): Finds the dropdown element using a CSS selector.
  • .select(valueOrTextOrIndex): Chooses the option by its value attribute, visible text, or index number.

This command triggers the change event automatically.

javascript
cy.get('select').select('optionValue')
๐Ÿ’ป

Example

This example shows how to select an option by visible text from a dropdown with id country. It also asserts that the correct option is selected.

javascript
describe('Dropdown selection test', () => {
  it('selects an option by visible text', () => {
    cy.visit('https://example.cypress.io/commands/actions')
    cy.get('#country').select('Canada')
    cy.get('#country').should('have.value', 'ca')
  })
})
Output
Test passes if the dropdown option 'Canada' is selected and its value is 'ca'.
โš ๏ธ

Common Pitfalls

Common mistakes when selecting dropdowns in Cypress include:

  • Using .click() instead of .select() on <select> elements, which won't change the selected option properly.
  • Trying to select options that do not exist or have incorrect values/text.
  • Not waiting for the page or dropdown to load before selecting.

Always verify the option exists and use .select() for dropdowns.

javascript
/* Wrong way: clicking option directly */
cy.get('select').click().get('option[value="ca"]').click()

/* Right way: use select() */
cy.get('select').select('ca')
๐Ÿ“Š

Quick Reference

CommandDescriptionExample
cy.get(selector).select(value)Selects option by value attributecy.get('select').select('us')
cy.get(selector).select(text)Selects option by visible textcy.get('select').select('United States')
cy.get(selector).select(index)Selects option by zero-based indexcy.get('select').select(2)
cy.get(selector).should('have.value', value)Asserts selected option's valuecy.get('select').should('have.value', 'us')
โœ…

Key Takeaways

Use cy.get() to find the dropdown and .select() to choose an option by value, text, or index.
Always verify the option exists before selecting to avoid test failures.
Avoid using .click() on select elements; .select() triggers proper change events.
Use assertions like .should('have.value', value) to confirm selection.
Wait for the dropdown to be visible and loaded before interacting.