How to Clear Input Fields in Cypress: Simple Guide
To clear an input field in Cypress, use the
.clear() command on the element selected by a locator, like cy.get('input').clear(). This removes any existing text so you can type fresh input or verify the field is empty.Syntax
The basic syntax to clear an input field in Cypress is:
cy.get(selector): Selects the input element using a CSS selector..clear(): Clears the value inside the selected input field.
javascript
cy.get('input').clear()
Example
This example shows how to clear a text input field with id username before typing new text:
javascript
describe('Clear input example', () => { it('clears the username input before typing', () => { cy.visit('https://example.cypress.io/commands/actions') cy.get('#username') .clear() .type('newUser') .should('have.value', 'newUser') }) })
Output
Test passes if the input is cleared and new text is typed correctly.
Common Pitfalls
Common mistakes when clearing inputs in Cypress include:
- Not selecting the correct input element, causing
.clear()to fail silently. - Trying to clear inputs that are disabled or readonly, which will not work.
- Using
.clear()on non-input elements likedivorspan.
Always ensure the element is visible and enabled before clearing.
javascript
cy.get('#wrongSelector').clear() // Wrong: selector does not match input // Correct usage: cy.get('input[name="email"]').clear()
Quick Reference
Summary tips for clearing inputs in Cypress:
- Use
cy.get(selector).clear()to clear input fields. - Ensure the input is visible and enabled.
- Chain
.clear()before typing new text. - Use precise selectors to avoid targeting wrong elements.
Key Takeaways
Use
.clear() on input elements to remove existing text in Cypress.Always select the correct and enabled input element before clearing.
Chain
.clear() before .type() to enter fresh input.Avoid using
.clear() on non-input or disabled elements.Verify the input is cleared by asserting its value after clearing.