0
0
Cypresstesting~15 mins

cy.select() for dropdowns in Cypress - Build an Automation Script

Choose your learning style9 modes available
Select an option from a dropdown and verify selection
Preconditions (1)
Step 1: Locate the dropdown menu with id 'country-select'
Step 2: Select the option with visible text 'Canada' from the dropdown
Step 3: Verify that the dropdown's selected value is 'Canada'
✅ Expected Result: The dropdown menu shows 'Canada' as the selected option after selection
Automation Requirements - Cypress
Assertions Needed:
Verify the dropdown has the selected value 'Canada'
Best Practices:
Use cy.get() with id selector for locating dropdown
Use cy.select() with visible text for selecting option
Use should('have.value', ...) assertion to verify selection
Avoid hardcoding XPath selectors
Use clear and descriptive test names
Automated Solution
Cypress
describe('Dropdown selection test', () => {
  it('Selects Canada from country dropdown and verifies selection', () => {
    cy.visit('https://example.com/dropdown-page');
    cy.get('#country-select').select('Canada');
    cy.get('#country-select').should('have.value', 'Canada');
  });
});

The test starts by visiting the page with the dropdown.

We locate the dropdown using cy.get('#country-select') which uses the id selector, a best practice for stable selectors.

Then we use .select('Canada') to pick the option with visible text 'Canada'. This is simple and clear.

Finally, we assert the dropdown's value is 'Canada' using should('have.value', 'Canada') to confirm the selection worked.

This approach avoids brittle selectors and uses Cypress commands consistently.

Common Mistakes - 4 Pitfalls
Using XPath selectors instead of id or class selectors
Using .click() on dropdown options instead of .select()
{'mistake': 'Not asserting the selected value after selection', 'why_bad': 'Without assertion, test does not verify if the selection actually happened.', 'correct_approach': "Always add an assertion like should('have.value', ...) to confirm the selection."}
Hardcoding URLs or test data inside the test without flexibility
Bonus Challenge

Now add data-driven testing to select and verify three different countries: 'Canada', 'USA', and 'Mexico'.

Show Hint