Home > database >  How to make CONDITIONAL STATEMENTS using SELECTORS on PLAYWRIGHT?
How to make CONDITIONAL STATEMENTS using SELECTORS on PLAYWRIGHT?

Time:09-17

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.

CodePudding user response:

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*
  • Related