skip to Main Content

I’m using spectrum web components to show a checkbox on a webpage. Here’s what I use on the site

<sp-checkbox size="m" data-test-id="test" checked="" tabindex="0" dir="ltr"></sp-checkbox>

When sp-checkbox is not checked, I want to click on it using the click(). I do the following in playwright

  testBtn = () => this.page.getByTestId("test");

  await this.testBtn().click();

testBtn refers to the sp-checkbox above on the website.

but it clicks on the checkbox regardless of whether it’s checked. I only want to click on the checkbox when it’s not checked.

How can I do this using playwright?

I tried the following but it doesn’t work

await this.testBtn().check()

2

Answers


  1. Try using CSS pseudo-class, like so:

    await page.locator('[data-test-id="test"]:not([checked=""])').click();
    Login or Signup to reply.
  2. const testBtn = () => this.page.getByTestId("test");
    
    const isChecked = await testBtn().isChecked();
    
    if (!isChecked) {
        await testBtn().click();
    }
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search