javascripttypescripttestingautomated-testsplaywright

How to make CONDITIONAL STATEMENTS using SELECTORS on PLAYWRIGHT?


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.


Solution

  • 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?