Cypress Clear Command

Profile picture for user arilio666

Clear command in Cypress is an action command that clears the value of an input or textarea. This command is an alias for 

.type('{selectall}{backspace}')

Syntax

.clear()
.clear(options)

Arguments Used In Clear Command

Options (Object): Can pass in objects to change the default behavior of .type(). Here is the list of some of the options that Cypress can use with the type command:

  1. animationDistanceThreshold: Used to consider the distance between the pixels and the element and that mist exceeds over time. Default is animationDistanceThreshold.
  2. force: Forces the action. Default is false.
  3. log: Displays the record in command log in output. Default is true.
  4. scrollBehavior: This is used to viewport position where an element should be scrolled before the command execution. Default is ScrollBehaviour.
  5. timeout: Used to input time to wait for the action to resolve before timing out. Default is defaultCommandTimeout.
  6. waitForAnimations: Waits for the animations to finish before executing the command. Default is waitForAnimations.

Usage

1. Correct Usage

cy.get('[type="type_here"]').clear() 
  • Clears type_here input
cy.get('textarea').type('Bye').clear() 
  • Clears textarea
cy.focused().clear() 
  • Clear focused input/textarea

2. Wrong Usage

cy.clear() 
  • It cannot be chained off 'cy.'
cy.get('nav').clear() 
  • 'get' doesn't yield input or textarea
cy.url().clear()
  • 'URL' doesn't yield a DOM element.

Cypress Clear Command Example

it('Type Username And Password',()=>{
    cy.visit('https://www.programsbuzz.com/user/login')
    cy.get('form').within(()=>{
        cy.xpath("//input[@id='edit-name']").type('Rataalada').clear()
        cy.get('#edit-pass').clear().type('bat')             
    })
})
  • Here is the username field. After typing in the text, it gets cleared of it.
  • In the password field, it gets cleared before typing in the input text.

Cypress Clear Command