Checking and unchecking

check(), not click()

click() toggles: if the box was already checked, it unchecks it. check() makes sure the box ends up checked and does nothing if it already is. That makes the test independent of the starting state.

const newsletter = page.getByRole('checkbox', { name: 'Subscribe to newsletter' });

await newsletter.check();
await expect(newsletter).toBeChecked();

await newsletter.uncheck();
await expect(newsletter).not.toBeChecked();

Set a state from data

When the desired state comes from a variable, use setChecked():

await page.getByLabel('Accept terms and conditions').setChecked(true);

Assert what the user sees too

The input being checked is only half the story. Also assert that the page reacted: here, the "Current state" card.

Checkbox examples

Current state

Newsletter: unchecked

Terms: unchecked