0
0
Cypresstesting~5 mins

cy.check() and cy.uncheck() in Cypress

Choose your learning style9 modes available
Introduction

We use cy.check() to select checkboxes or radio buttons in tests. cy.uncheck() is used to deselect checkboxes. This helps us test if the app reacts correctly when options are chosen or removed.

When testing a form where users select preferences using checkboxes.
When verifying that selecting a radio button triggers the right behavior.
When ensuring that unchecking a checkbox disables or hides certain options.
When automating tests for filters on a shopping site that use checkboxes.
When confirming that only one radio button can be selected at a time.
Syntax
Cypress
cy.get('selector').check()
cy.get('selector').uncheck()

Use cy.get() to find the checkbox or radio button before calling check() or uncheck().

check() works for both checkboxes and radio buttons, but uncheck() only works for checkboxes.

Examples
Selects the checkbox with id 'subscribe'.
Cypress
cy.get('#subscribe').check()
Selects the radio button with value 'male'.
Cypress
cy.get('input[type="radio"][value="male"]').check()
Deselects the checkbox with class 'terms-checkbox'.
Cypress
cy.get('.terms-checkbox').uncheck()
Sample Program

This test visits a page with checkboxes and radio buttons. It checks the first checkbox, verifies it is checked, then unchecks it and verifies it is unchecked. Finally, it checks the first radio button and verifies it is checked.

Cypress
describe('Checkbox and Radio Button Test', () => {
  it('checks and unchecks inputs correctly', () => {
    cy.visit('https://example.cypress.io/commands/actions')

    // Check a checkbox
    cy.get('.action-checkboxes [type="checkbox"]').first().check().should('be.checked')

    // Uncheck the same checkbox
    cy.get('.action-checkboxes [type="checkbox"]').first().uncheck().should('not.be.checked')

    // Check a radio button
    cy.get('.action-radios [type="radio"]').first().check().should('be.checked')
  })
})
OutputSuccess
Important Notes

Always use unique and clear selectors to avoid selecting the wrong checkbox or radio button.

Trying to uncheck() a radio button will cause an error because radios cannot be unchecked by user action.

Use should('be.checked') or should('not.be.checked') to assert the state after checking or unchecking.

Summary

cy.check() selects checkboxes or radio buttons.

cy.uncheck() deselects checkboxes only.

Use assertions to confirm the input state after actions.