Back to All Questions
Question 25 of 100
Interactions
Beginner
How to handle a checkbox using Playwright?
The Answer
Checkboxes use `.check()`, `.uncheck()`, and `.setChecked(bool)`. The `.setChecked()` method is the most robust as it works regardless of current state.
Deep Dive Explanation
`.setChecked(true/false)` is preferred in data-driven tests because it ensures the correct state regardless of the checkbox's current state, preventing double-toggling bugs.
example.spec.ts
const agreeCheckbox = page.getByLabel('I agree to Terms');
// Check it
await agreeCheckbox.check();
await expect(agreeCheckbox).toBeChecked();
// Uncheck it
await agreeCheckbox.uncheck();
// Set state conditionally (most robust)
await agreeCheckbox.setChecked(true);
await agreeCheckbox.setChecked(false);