Cypress equips you with the versatile .select() method, enabling you to interact with dropdowns created using the <select> and <option> tags. This method allows you to select options by their value, visible text, or index, giving you the power to handle any drop-down scenario.
Example:
Suppose you have the following HTML:
<select id="dropdown"> <option value="option1">Option 1</option> <option value="option2">Option 2</option> <option value="option3">Option 3</option> </select>
Here are some examples of how to select an option in Cypress using its value, visible text, or index:
describe('Handling HTML Select Dropdown', () => {
it('should select an option by its value', () => {
cy.visit('https://example.com');
// Select an option by its value
cy.get('#dropdown').select('option1');
// Verify the selected value
cy.get('#dropdown').should('have.value', 'option1');
});
});
describe('Handling HTML Select Dropdown', () => {
it('should select an option by its visible text', () => {
cy.visit('https://example.com');
// Select an option by its visible text
cy.get('#dropdown').select('Option 2');
// Verify the selected value
cy.get('#dropdown').should('have.value', 'option2');
});
});
describe('Handling HTML Select Dropdown', () => {
it('should select an option by its index', () => {
cy.visit('https://example.com');
// Select an option by its index (0-based)
cy.get('#dropdown').select(2);
// Verify the selected value
cy.get('#dropdown').should('have.value', 'option3');
});
});
This approach allows you to handle and test select dropdowns in your Cypress tests effectively.