0
0
Cypresstesting~15 mins

cy.check() and cy.uncheck() in Cypress - Build an Automation Script

Choose your learning style9 modes available
Verify checkbox can be checked and unchecked
Preconditions (1)
Step 1: Locate the checkbox with id 'subscribe-newsletter'
Step 2: Check the checkbox
Step 3: Verify the checkbox is checked
Step 4: Uncheck the checkbox
Step 5: Verify the checkbox is unchecked
✅ Expected Result: The checkbox is checked after checking and unchecked after unchecking
Automation Requirements - Cypress
Assertions Needed:
Verify checkbox is checked after cy.check()
Verify checkbox is unchecked after cy.uncheck()
Best Practices:
Use cy.get() with id selector for locating checkbox
Use explicit assertions with .should('be.checked') and .should('not.be.checked')
Avoid hardcoded waits; rely on Cypress automatic waits
Automated Solution
Cypress
describe('Checkbox check and uncheck test', () => {
  beforeEach(() => {
    cy.visit('https://example.com/checkbox-demo');
  });

  it('should check and uncheck the newsletter subscription checkbox', () => {
    cy.get('#subscribe-newsletter')
      .check()
      .should('be.checked');

    cy.get('#subscribe-newsletter')
      .uncheck()
      .should('not.be.checked');
  });
});

The test starts by visiting the checkbox demo page in the beforeEach hook to ensure a fresh state before each test.

We locate the checkbox using cy.get('#subscribe-newsletter'), which uses the id selector for clarity and speed.

We then use .check() to check the checkbox and immediately assert it is checked with .should('be.checked').

Next, we use .uncheck() to uncheck the checkbox and assert it is unchecked with .should('not.be.checked').

This approach uses Cypress's built-in waiting and assertion mechanisms, avoiding any manual waits or flaky code.

Common Mistakes - 3 Pitfalls
Using cy.click() instead of cy.check() to check a checkbox
{'mistake': 'Not asserting the checkbox state after checking or unchecking', 'why_bad': 'Without assertions, the test does not verify if the action succeeded, making the test unreliable.', 'correct_approach': "Always add assertions like .should('be.checked') or .should('not.be.checked') after actions."}
Using overly complex or fragile selectors like XPath or nth-child for checkboxes
Bonus Challenge

Now add data-driven testing to check and uncheck three different checkboxes with ids 'subscribe-newsletter', 'accept-terms', and 'receive-updates'.

Show Hint