0
0
Cypresstesting~15 mins

cy.check() and cy.uncheck() in Cypress - Deep Dive

Choose your learning style9 modes available
Overview - cy.check() and cy.uncheck()
What is it?
cy.check() and cy.uncheck() are commands in Cypress used to interact with checkbox and radio button elements on a web page. cy.check() selects or checks these elements, while cy.uncheck() deselects or unchecks checkboxes. These commands simulate user actions to test how the application responds to selecting or deselecting options.
Why it matters
Testing checkboxes and radio buttons is essential because they control user choices and form inputs. Without these commands, automated tests would struggle to verify if the UI behaves correctly when users select or deselect options. This could lead to bugs in forms, settings, or filters going unnoticed, affecting user experience and data accuracy.
Where it fits
Before learning cy.check() and cy.uncheck(), you should understand basic Cypress commands and selectors to find elements on a page. After mastering these commands, you can move on to testing form submissions, validations, and complex user interactions involving multiple input types.
Mental Model
Core Idea
cy.check() and cy.uncheck() simulate a user clicking to select or deselect checkboxes and radio buttons, ensuring the UI reacts as expected.
Think of it like...
It's like flipping a light switch on or off to see if the room lights up or goes dark, testing if the switch controls the light properly.
┌───────────────┐       ┌───────────────┐
│ Checkbox      │       │ Radio Button  │
│ [ ] unchecked│       │ ( ) unselected│
└──────┬────────┘       └──────┬────────┘
       │ cy.check()               │ cy.check()
       ▼                         ▼
┌───────────────┐       ┌───────────────┐
│ Checkbox      │       │ Radio Button  │
│ [x] checked  │       │ (•) selected  │
└───────────────┘       └───────────────┘

cy.uncheck() reverses checkbox from checked to unchecked.
Build-Up - 7 Steps
1
FoundationUnderstanding checkboxes and radios
🤔
Concept: Learn what checkboxes and radio buttons are and how users interact with them.
Checkboxes allow multiple selections; radio buttons allow only one selection in a group. Users click to toggle checkboxes on or off, or select one radio button among many.
Result
You can identify when an option is selected or not based on the element's state.
Knowing the difference between checkboxes and radio buttons helps you choose the right Cypress command and test approach.
2
FoundationSelecting elements with Cypress
🤔
Concept: Learn how to find checkboxes or radio buttons on the page using Cypress selectors.
Use cy.get() with CSS selectors or attributes like name, id, or data-test to locate the input elements you want to test.
Result
You can target the exact checkbox or radio button to interact with.
Precise element selection is crucial to avoid testing the wrong element or causing flaky tests.
3
IntermediateUsing cy.check() to select options
🤔Before reading on: do you think cy.check() works only on checkboxes or also on radio buttons? Commit to your answer.
Concept: cy.check() simulates a user clicking to select a checkbox or radio button, changing its state to checked or selected.
Example: cy.get('input[type="checkbox"]').check() cy.get('input[type="radio"][value="option1"]').check() This triggers the browser's native behavior and any event listeners attached.
Result
The targeted checkbox or radio button becomes selected, and the UI updates accordingly.
Understanding that cy.check() triggers real browser events ensures your tests reflect actual user interactions.
4
IntermediateUsing cy.uncheck() to deselect checkboxes
🤔Before reading on: do you think cy.uncheck() works on radio buttons as well as checkboxes? Commit to your answer.
Concept: cy.uncheck() simulates a user clicking to deselect a checkbox, changing its state to unchecked. It does not work on radio buttons because they cannot be deselected by clicking again.
Example: cy.get('input[type="checkbox"]').uncheck() This triggers the native uncheck behavior and any related events.
Result
The targeted checkbox becomes unchecked, and the UI updates accordingly.
Knowing that cy.uncheck() only applies to checkboxes prevents test errors and confusion.
5
IntermediateHandling multiple checkboxes at once
🤔
Concept: You can check or uncheck multiple checkboxes by passing an array of values or using selectors that match multiple elements.
Example: cy.get('input[type="checkbox"]').check(['option1', 'option3']) cy.get('input[type="checkbox"]').uncheck(['option2']) This simulates checking or unchecking multiple boxes in one command.
Result
Multiple checkboxes change state as specified, simplifying tests with many options.
Batch operations reduce test code and improve readability when dealing with groups of checkboxes.
6
AdvancedDealing with hidden or disabled inputs
🤔Before reading on: do you think cy.check() can check a hidden or disabled checkbox by default? Commit to your answer.
Concept: By default, cy.check() and cy.uncheck() only work on visible and enabled inputs. You can override this with options to force the action on hidden or disabled elements.
Example: cy.get('#hiddenCheckbox').check({ force: true }) cy.get('#disabledCheckbox').uncheck({ force: true }) Use this carefully as it may not reflect real user behavior.
Result
The checkbox state changes even if the element is hidden or disabled, allowing tests of edge cases.
Understanding the force option helps test complex UI states but warns against unrealistic user scenarios.
7
ExpertEvent triggering and side effects
🤔Before reading on: do you think cy.check() only changes the checkbox state or also triggers all related events? Commit to your answer.
Concept: cy.check() and cy.uncheck() trigger native DOM events like click, input, and change, ensuring event handlers run as if a real user interacted.
This means your application’s JavaScript reacts normally, updating UI or data models. If you manually change the checkbox property without these commands, events may not fire, causing tests to miss bugs.
Result
Tests accurately simulate user behavior, catching issues related to event-driven logic.
Knowing that these commands trigger events prevents false positives and ensures your tests cover real user interactions.
Under the Hood
cy.check() and cy.uncheck() locate the input element in the DOM, verify it is visible and enabled (unless forced), then simulate a user click event. This triggers the browser's native behavior to toggle the checked property and fires associated events like click, input, and change. Cypress waits for these events to complete before moving on, ensuring synchronization with the app's state.
Why designed this way?
These commands were designed to mimic real user interactions as closely as possible to catch UI bugs that only appear during actual use. Alternatives like directly setting properties would not trigger event listeners, leading to incomplete tests. The force option was added to handle edge cases where UI elements are hidden or disabled but still need testing.
┌───────────────┐
│ cy.check()    │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Find element  │
│ (selector)    │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Check visible │
│ and enabled?  │
└──────┬────────┘
       │ Yes
       ▼
┌───────────────┐
│ Simulate click│
│ and events    │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Update checked│
│ property     │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Can cy.uncheck() be used to deselect a radio button? Commit to yes or no.
Common Belief:cy.uncheck() works on both checkboxes and radio buttons to deselect them.
Tap to reveal reality
Reality:cy.uncheck() only works on checkboxes. Radio buttons cannot be deselected by clicking again; selecting another radio button changes the selection.
Why it matters:Using cy.uncheck() on radio buttons causes test failures or no effect, leading to confusion and wasted debugging time.
Quick: Does cy.check() change the checkbox state without triggering any events? Commit to yes or no.
Common Belief:cy.check() only changes the checkbox's checked property silently without firing events.
Tap to reveal reality
Reality:cy.check() triggers all native events like click, input, and change, simulating real user interaction.
Why it matters:Assuming no events fire can cause tests to miss bugs in event handlers or UI updates.
Quick: Can cy.check() check a hidden or disabled checkbox by default? Commit to yes or no.
Common Belief:cy.check() can check any checkbox regardless of visibility or disabled state.
Tap to reveal reality
Reality:By default, cy.check() only works on visible and enabled checkboxes. You must use { force: true } to override this.
Why it matters:Ignoring visibility and enabled checks can cause tests to pass unrealistically or fail unexpectedly.
Quick: Does cy.check() accept multiple values to check several checkboxes at once? Commit to yes or no.
Common Belief:cy.check() can only check one checkbox at a time.
Tap to reveal reality
Reality:cy.check() accepts an array of values to check multiple checkboxes in one command.
Why it matters:Not knowing this leads to verbose tests and missed opportunities for cleaner code.
Expert Zone
1
cy.check() triggers native DOM events in a specific order (mousedown, mouseup, click, input, change), which can affect event handler behavior in subtle ways.
2
Using { force: true } bypasses Cypress's built-in checks but can cause tests to interact with elements users cannot, so it should be used sparingly and with caution.
3
When multiple checkboxes share the same name attribute, cy.check() can target them by value, but ambiguous selectors can cause flaky tests if values are not unique.
When NOT to use
Avoid using cy.check() and cy.uncheck() on custom-styled checkboxes or radio buttons that do not use native input elements. Instead, use cy.click() on the visible custom control. For non-interactive elements or when testing logic without UI, consider unit tests or mocking instead.
Production Patterns
In real-world tests, cy.check() and cy.uncheck() are often combined with assertions to verify side effects, such as: cy.get('input[type="checkbox"]').check().should('be.checked') cy.get('input[type="checkbox"]').uncheck().should('not.be.checked') They are also used in form testing suites to simulate user input and validate form submission behavior.
Connections
Event-driven programming
cy.check() triggers DOM events that drive event-driven programming in web apps.
Understanding how cy.check() fires events helps grasp how user actions propagate through event listeners to update app state.
User experience (UX) testing
Checking and unchecking inputs simulates real user choices, connecting functional testing to UX validation.
Testing input interactions ensures the app responds intuitively, preventing frustrating user experiences.
Electrical switches
Both cy.check()/uncheck() and electrical switches toggle states on or off.
Recognizing this parallel helps understand the binary nature of checkboxes and the importance of state changes.
Common Pitfalls
#1Trying to uncheck a radio button using cy.uncheck(), expecting it to deselect.
Wrong approach:cy.get('input[type="radio"]').uncheck()
Correct approach:cy.get('input[type="radio"][value="option2"]').check()
Root cause:Misunderstanding that radio buttons cannot be deselected directly; selecting another radio button changes the selection.
#2Using cy.check() on a hidden checkbox without forcing, causing the test to fail.
Wrong approach:cy.get('#hiddenCheckbox').check()
Correct approach:cy.get('#hiddenCheckbox').check({ force: true })
Root cause:Not realizing Cypress blocks actions on hidden elements by default to mimic real user behavior.
#3Selecting checkboxes by ambiguous selectors causing multiple unintended elements to be checked.
Wrong approach:cy.get('input[type="checkbox"]').check('option1')
Correct approach:cy.get('input[type="checkbox"][value="option1"]').check()
Root cause:Using broad selectors without specifying unique attributes leads to flaky or incorrect tests.
Key Takeaways
cy.check() and cy.uncheck() simulate real user clicks to select or deselect checkboxes and radio buttons, triggering all related events.
cy.uncheck() only works on checkboxes; radio buttons cannot be deselected directly and require selecting another option.
By default, these commands only act on visible and enabled elements; use { force: true } carefully for hidden or disabled inputs.
You can check or uncheck multiple checkboxes at once by passing arrays of values, simplifying test code.
Understanding event triggering and element state changes ensures your tests accurately reflect user interactions and catch real bugs.