3 Different Ways to Clear Inputs in Cypress

3 Different Ways to Clear Inputs in Cypress

Ferenc Almasi β€’ 2022 August 14 β€’ πŸ“– 2 min read
  • twitter
  • facebook

To clear input fields in Cypress, we need to use the clear command chained off of from cy.get:

cy.get('input').clear({ force: true })
Copied to clipboard!

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:

Clearing the currently focused input
Copied to clipboard!

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:

Copied to clipboard!

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', '')
Copied to clipboard!

Want to learn Cypress from end to end? Check out my Cypress course on Educative where I cover everything:

Learn Cypress with Educative
3 Different Ways to Clear Inputs in Cypress
If you would like to see more webtips, followΒ @flowforfrank
Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
Master JavaScript


Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Unlimited access to hundred of tutorials
  • check Access to exclusive interactive lessons
  • check Remove ads to learn without distractions
Become a Pro