Cypress - Element Interactions
How would you write a Cypress test to check a checkbox only if it is not already checked?
You want to check only if not already checked, so you need to inspect the element's state first.
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.
15+ quiz questions · All difficulty levels · Free
Free Signup - Practice All Questions