Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i clear a multi-select input using Cypress?

Tags:

cypress

How do i clear (deselect) all options within a multi-select input using Cypress?

The documentation here does not seem to cover this scenario: https://docs.cypress.io/api/commands/select.html#Syntax

The clear() command apparently cannot be applied to selects, as you might expect https://docs.cypress.io/api/commands/clear.html#Syntax

I have tried passing an empty string / array / null to select() but i get the following error:

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

like image 851
rich.3po Avatar asked Nov 15 '25 22:11

rich.3po


1 Answers

Since Cypress 8.6.0, this is supported in Cypress: https://stackoverflow.com/a/69537449/3474615


Before 8.6.0:

You can use cy.invoke() to call the .val('') method on the underlying JQuery element, which will cause it to be cleared.

Like this:

cy.get('select')
.invoke('val', '')

Note that this will not emit the change event. If you want to test that your code reacts to the change event, you can cause it to be emitted with cy.trigger():

cy.get('select')
.invoke('val', '')
.trigger('change')

I've also filed a feature request for this functionality, as it does seem like something that should be included with Cypress by default.

like image 170
Zach Bloomquist Avatar answered Nov 18 '25 19:11

Zach Bloomquist