3 Different Ways to Clear Inputs in Cypress
To clear input fields in Cypress, we need to use the clear
command chained off of from cy.get
:
cy.get('input').clear()
cy.get('input').clear({ force: true })
The clear command also accepts a configuration object where you can configure how the command should behave. For example, by passing a force
attribute, we can force the field to be cleared.
If you set force
on the clear
command, Cypress will skip checking for actionability - whether the input element can be interacted with. For example, if it is visible and not disabled.
You can also use the cy.focused
command in order to get the focused element on the page and initiate a clear on that:
cy.focused().clear()
Preferably, you want to use the clear
command to clear input fields in Cypress, but there are two other ways you can also clear inputs. One of them is using the type
command:
cy.get('input').type('{selectall}{backspace}')
This is using a special character sequence to tell Cypress to select the contents of the input and hit backspace to clear the value. cy.clear
is in fact an alias for the above command. Lastly, you can also use invoke to set the value
property of the field to an empty value.
cy.get('input').invoke('val', '')
Want to learn Cypress from end to end? Check out my Cypress course on Educative where I cover everything:
Resources:
Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: