Search code examples
automated-testsplaywrightplaywright-typescript

How to interact with a hidden element (toggle/checkbox)?


I am trying to click an input html element with attribute type="checkbox". However it seems to be hidden. How can I get around this?

I initially tried interacting with it using the .setChecked() and unCheck() functions. When that didn't work I tried using javascript with the following line:

await this.page.evaluate(`document.querySelector('selector').click()`);

This also does not work, in the console I can see this returns undefined. Also, when debugging in the console I noticed that running:

document.querySelector('selector').checkVisibility(); 

returns false


Solution

  • Usually, you'd want to identify the checkbox using one of the more modern forms of locator and then force the check to take place regardless of the actionability checks that would usually be required:

    await page.getByRole('checkbox').setChecked(true, {force: true});
    

    or

    await page.getByLabel('Checkbox label').check({force: true});
    

    You can use either method, setChecked or check, they both accept "force".