Bird
0
0

You want to click a checkbox only if it is not already checked. Which Cypress code correctly does this?

hard📝 Application Q15 of 15
Cypress - Element Interactions
You want to click a checkbox only if it is not already checked. Which Cypress code correctly does this?
Acy.get('#agree').check()
Bcy.get('#agree').then($el => { if (!$el.is(':checked')) { cy.wrap($el).click() } })
Ccy.get('#agree').click({ force: true })
Dcy.get('#agree').click()
Step-by-Step Solution
Solution:
  1. Step 1: Understand the requirement

    You want to click the checkbox only if it is not checked yet, to avoid toggling it off accidentally.
  2. Step 2: Analyze each option

    cy.get('#agree').then($el => { if (!$el.is(':checked')) { cy.wrap($el).click() } }) uses then to check if the checkbox is unchecked, then clicks it. cy.get('#agree').click({ force: true }) forces a click regardless of state. cy.get('#agree').check() uses check(), which is a better way to check a checkbox but not a click. cy.get('#agree').click() clicks unconditionally.
  3. Step 3: Choose the best option

    cy.get('#agree').then($el => { if (!$el.is(':checked')) { cy.wrap($el).click() } }) correctly checks the state and clicks only if unchecked, matching the requirement.
  4. Final Answer:

    cy.get('#agree').then($el => { if (!$el.is(':checked')) { cy.wrap($el).click() } }) -> Option B
  5. Quick Check:

    Check state before click to avoid toggling off [OK]
Quick Trick: Check checkbox state before clicking to avoid toggling [OK]
Common Mistakes:
  • Clicking checkbox without checking state
  • Using click({ force: true }) unnecessarily
  • Confusing click() with check()

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Cypress Quizzes