How to make CONDITIONAL STATEMENTS using SELECTORS on PLAYWRIGHT?

Viewed 3304

I need some help to make conditional statements using Playwright tests.
I have a given selector, let's say a button, and I need to write a conditional statement like this:

if (selector is not present/visible)

    do nothing and proceed with the *next lines of code*

else  

    await page.click(*selector*)

*next lines of code*

Is there any efficient way to do these kinds of things? I didn't found anything in the Playwright documentation.

4 Answers

It can be implemented in JavaScript similarly to your pseudo-code using page.$(selector), which returns null if the specified element is not in the DOM. (Note: watch for the right usage of parenthesis inside the condition!)

I'd also reverse your initial if(falsy)...else condition into a single if(truthy), as you want to execute a command only if the selector exists, the else branch doesn't make too much sense:

if ((await page.$('#elem-id')) !== null) {
  await page.click('#elem-id')
}
// code goes on with *next lines of code*

Since Playwright recommends using Locators over EventHandles (citation), you could also use:

async function clickIfNotNull(page, selector){
    const yourLocator = await page.locator(selector)
    const elementIsNotNull = await yourLocator.evaluate(elem => elem !== null);
    if (elementIsNotNull) {
        await yourLocator.click()
    }
}

Despite Playwright's recommendation around using Locators, if

if ((await page.$('#elem-id')) !== null) {
  await page.click('#elem-id')
}
// code goes on with *next lines of code*

Does the job fine, would this solution be ok to use?

I would like to share another solution that a colleague who is mentoring me created that also worked perfectly fine and might be even simpler than the previous answers.

    if (await page.isVisible('#element-id'))
{
   await page.click('#element-id');
}

When testing this in Playwright it works as well as other statements detailed before. There is a change to add an else with no problem as well.

Related