3 Different Ways to Clear Inputs in Cypress

3 Different Ways to Clear Inputs in Cypress

Ferenc Almasi β€’ 2022 August 14 β€’ Read time 2 min read
  • twitter
  • facebook

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

Copied to clipboard!
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:

Copied to clipboard!
cy.focused().clear()
Clearing the currently focused input

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!
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.

Copied to clipboard!
cy.get('input').invoke('val', '')

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

Resources:

  • twitter
  • facebook
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.