Bird
0
0

You want to clear an input field only if it contains any text. Which Cypress code snippet correctly does this?

hard📝 Application Q9 of 15
Cypress - Element Interactions
You want to clear an input field only if it contains any text. Which Cypress code snippet correctly does this?
Acy.get('input#search').clear().should('have.value', '')
Bcy.get('input#search').invoke('val').then(val => { if(val) cy.get('input#search').clear() })
Ccy.get('input#search').type('{selectall}{backspace}')
Dcy.get('input#search').clear(true)
Step-by-Step Solution
Solution:
  1. Step 1: Check current input value

    Use invoke('val') to get the current value of the input.
  2. Step 2: Conditionally clear if value exists

    Inside then, clear only if the value is not empty.
  3. Final Answer:

    cy.get('input#search').invoke('val').then(val => { if(val) cy.get('input#search').clear() }) -> Option B
  4. Quick Check:

    Use invoke('val') + conditional clear = A [OK]
Quick Trick: Use invoke('val') to check input before clearing [OK]
Common Mistakes:
  • Clearing unconditionally without checking value
  • Using invalid clear(true) parameter
  • Using type('{selectall}{backspace}') without condition

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Cypress Quizzes