How to Check Checkbox in Cypress: Simple Guide
In Cypress, you can check a checkbox using the
.check() command on a checkbox element. Use cy.get('selector').check() to select and check the checkbox in your test.Syntax
The basic syntax to check a checkbox in Cypress is:
cy.get('selector'): Finds the checkbox element using a CSS selector..check(): Checks the checkbox if it is not already checked.
javascript
cy.get('input[type="checkbox"]').check()
Example
This example shows how to check a checkbox with id subscribe and verify it is checked.
javascript
describe('Checkbox Test', () => { it('checks the subscribe checkbox', () => { cy.visit('https://example.com/form') cy.get('#subscribe').check() cy.get('#subscribe').should('be.checked') }) })
Output
Test passes if the checkbox with id 'subscribe' is checked after the command.
Common Pitfalls
Common mistakes when checking checkboxes in Cypress include:
- Using
.click()instead of.check(), which may not work reliably for checkboxes. - Not selecting the correct checkbox element with the right selector.
- Trying to check a disabled or hidden checkbox, which will cause the test to fail.
Always use .check() for checkboxes and ensure the element is visible and enabled.
javascript
/* Wrong way: Using click() may fail */ cy.get('#subscribe').click() /* Right way: Use check() */ cy.get('#subscribe').check()
Quick Reference
| Command | Description |
|---|---|
| cy.get('selector').check() | Checks the checkbox matching the selector |
| cy.get('selector').uncheck() | Unchecks the checkbox matching the selector |
| cy.get('selector').should('be.checked') | Asserts the checkbox is checked |
| cy.get('selector').should('not.be.checked') | Asserts the checkbox is not checked |
Key Takeaways
Use cy.get('selector').check() to check a checkbox in Cypress.
Always select the correct checkbox element with a precise selector.
Avoid using .click() on checkboxes; prefer .check() for reliability.
Verify the checkbox state with assertions like .should('be.checked').
Ensure the checkbox is visible and enabled before checking it.