Software Development and QA Tips By QASource Experts

How to Handle Dropdown in Cypress

Written by QASource Engineering Team | Jul 29, 2024 4:00:00 PM

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>
  

Steps to Handle

  • Identify the select element using cy.get()
  • Use the .select() command to choose an option by its value, visible text, or index
  • Optionally, verify the selected option
 

Cypress Test Examples

Here are some examples of how to select an option in Cypress using its value, visible text, or index:

Select an Option by Value

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');
	  });
	});
  

Select an Option by Visible Text

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');
	  });
	});
     

Select an Option by Index

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');
	  });
	});
   
 

Conclusion

  • Identify the Select Element: Use cy.get('#dropdown') to locate the dropdown element. The # symbol targets an element by its id attribute.
  • Select an Option: Use .select('value'), .select('Visible Text'), or .select(index).
  • Verify the Selection: Use .should('have.value', 'expectedValue') to ensure the correct option is selected.

This approach allows you to handle and test select dropdowns in your Cypress tests effectively.