Bird
0
0

How would you write a Cypress test to check a checkbox only if it is not already checked?

hard📝 Application Q9 of 15
Cypress - Element Interactions
How would you write a Cypress test to check a checkbox only if it is not already checked?
Acy.get('input[type="checkbox"]').then($el => { if (!$el.is(':checked')) cy.wrap($el).check() })
Bcy.get('input[type="checkbox"]').check()
Ccy.get('input[type="checkbox"]').uncheck().check()
Dcy.get('input[type="checkbox"]').should('not.be.checked').check()
Step-by-Step Solution
Solution:
  1. Step 1: Understand conditional checking

    You want to check only if not already checked, so you need to inspect the element's state first.

  2. Step 2: Analyze options

    cy.get('input[type="checkbox"]').then($el => { if (!$el.is(':checked')) cy.wrap($el).check() }) uses then() to get the element and conditionally calls check() if not checked. cy.get('input[type="checkbox"]').check() always checks without condition. cy.get('input[type="checkbox"]').uncheck().check() unchecks first which is unnecessary. cy.get('input[type="checkbox"]').should('not.be.checked').check() asserts not checked but will fail if already checked.

  3. Final Answer:

    cy.get('input[type="checkbox"]').then($el => { if (!$el.is(':checked')) cy.wrap($el).check() }) -> Option A
  4. Quick Check:

    Use then() and condition to check only if unchecked [OK]
Quick Trick: Use then() with condition to check only if unchecked [OK]
Common Mistakes:
  • Always checking without condition
  • Unchecking before checking unnecessarily
  • Using should() which fails if condition not met

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Cypress Quizzes