Cypress 8.6.0 - Unselect all selected options with cy.select([])

Cypress handles static dropdowns with the help of the select() command. For a static dropdown, the tag name of the element should be <select> and its child elements should have the tag name <option>. We can select values by passing texts or indexes. In this blog, we will see how we can unselect all dropdown values by passing an empty array.

Syntax

.select(value)
.select(values)
.select(value, options)
.select(values, options)

Before

Before version 8.6.0, we would get an error if an empty array was passed into cy.select().

Consider the following snippet to understand the usage better.

<select multiple>
  <option value="foo">Foo</option>
  <option value="bar">Bar</option>
  <option value="nest">Nest</option>
</select>

It follows the existing pattern that passing an array into cy.select() will unselect the other options.

// Select all 3 options in the dropdown using array of texts
cy.get('select').select(['Foo', 'Bar', 'Nest']);

// Select all 3 options in the dropdown by passing their indexes
cy.get('select').select([0, 1, 2]);

// Select only 'Foo' and unselect all others
cy.get('select').select(['Foo']);

// Select only 'Foo' using index and unselect all others
cy.get('select').select([0]);

// Pass empty array into select will give below error
cy.get('select').select([]);

`CypressError: cy.select() failed because it could not find a single <option> with value or text matching`

After

With the updated Cypress 8.6.0, we can use cy.select([]) to clear any selected options in a multi-value select. Previously, an error would be thrown if an empty array was passed into cy.select().

<select multiple>
  <option value="foo">Foo</option>
  <option value="bar">Bar</option>
  <option value="nest">Nest</option>
</select>

// Select all 3 options in the dropdown using array of texts
cy.get('select').select(['Foo', 'Bar', 'Nest']);

// Unselect all options at once
cy.get('select').select([]);

To know more check out this PR.

Need help on your Ruby on Rails or React project?

Join Our Newsletter