0
0
Cypresstesting~15 mins

cy.clear() for input fields in Cypress - Build an Automation Script

Choose your learning style9 modes available
Clear text from an input field using cy.clear()
Preconditions (2)
Step 1: Navigate to the web page containing the input field
Step 2: Type 'testuser' into the input field with id 'username'
Step 3: Use cy.clear() to clear the input field
Step 4: Verify that the input field is empty after clearing
✅ Expected Result: The input field with id 'username' is empty after calling cy.clear()
Automation Requirements - Cypress
Assertions Needed:
Verify the input field contains 'testuser' after typing
Verify the input field is empty after cy.clear()
Best Practices:
Use cy.get() with id selector for locating the input field
Chain commands properly to ensure correct execution order
Use should('have.value', '') assertion to verify clearing
Avoid hardcoded waits; rely on Cypress automatic waits
Automated Solution
Cypress
describe('Input field clear test', () => {
  it('should clear the input field using cy.clear()', () => {
    cy.visit('https://example.com');
    cy.get('#username')
      .type('testuser')
      .should('have.value', 'testuser')
      .clear()
      .should('have.value', '');
  });
});

This test visits the target page, selects the input field by its id username, types the text testuser, and asserts the input contains that text. Then it calls cy.clear() to clear the input field and asserts that the input is empty by checking its value is an empty string. Using chaining ensures commands run in order and Cypress waits automatically for each step to complete.

Common Mistakes - 3 Pitfalls
Using cy.clear() without first selecting the input field
{'mistake': 'Not asserting the input value after clearing', 'why_bad': 'Without an assertion, you cannot confirm if the input was actually cleared, reducing test reliability.', 'correct_approach': "Use should('have.value', '') after cy.clear() to verify the input is empty."}
Using hardcoded waits like cy.wait() instead of relying on Cypress automatic waits
Bonus Challenge

Now add data-driven testing with 3 different input values to verify clearing works for each

Show Hint