0
0
Cypresstesting~5 mins

cy.clear() for input fields in Cypress

Choose your learning style9 modes available
Introduction

We use cy.clear() to remove any text inside input boxes. This helps us start fresh before typing new text.

When you want to erase old text before entering new data in a form.
When testing if an input field can be cleared by the user.
When resetting a form field during automated tests.
When verifying that clearing an input updates the page correctly.
Syntax
Cypress
cy.get('inputSelector').clear()

cy.get() finds the input field using a selector.

clear() empties the input field's text.

Examples
Clears the input field with id username.
Cypress
cy.get('#username').clear()
Clears the input field with the name attribute email.
Cypress
cy.get('input[name="email"]').clear()
Clears the input field with class search-box.
Cypress
cy.get('.search-box').clear()
Sample Program

This test visits a page, clears the input box, types an email into it, checks the text is there, then clears it and checks the box is empty.

Cypress
describe('Clear input field test', () => {
  it('clears the input box before typing', () => {
    cy.visit('https://example.cypress.io/commands/actions')
    cy.get('.action-email')
      .clear()
      .type('hello@example.com')
      .should('have.value', 'hello@example.com')
      .clear()
      .should('have.value', '')
  })
})
OutputSuccess
Important Notes

If the input is disabled or readonly, clear() will not work.

Always use a reliable selector to find the input field.

Summary

cy.clear() empties text from input fields.

Use it before typing new text to avoid leftover data.

Works only on editable input fields.