Ambassador Kosh
Ambassador Kosh

Reputation: 511

Playwright testing. Can I use a variable in ':has-text()'

Using Playwright, I'd like to find an element using the value of a variable

For example:

let name = 'Sully'
await page.click(`li:has-text(${sully})`)

but I get the following error:

page.click: Error: "has-text" engine expects a single string

Upvotes: 3

Views: 6415

Answers (2)

Vishal Aggarwal
Vishal Aggarwal

Reputation: 4171

Don't use css based selectors directly or even Page.click()

These are not recommended by playwright docs anymore.

"XPath and CSS selectors can be tied to the DOM structure or implementation. These selectors can break when the DOM structure changes. Long CSS or XPath chains can lead to unstable tests."

Page.click is also discouraged.

Use Locators with filters instead:

In comparison, locators are dynamic and don't depend on page structure.

 let name = 'Sully'
 await page
    .getByRole('listitem')
    .filter({ hasText: name})
    .click();

Upvotes: 2

Yevhen Laichenkov
Yevhen Laichenkov

Reputation: 8652

You have to add single or double quotes to the has-text function and use the name variable instead of sully or declare it.

Hence, it should be like this:

let name = 'Sully';

//                            ↓       ↓ - missed quotes       
await page.click(`li:has-text('${name}')`)

Upvotes: 9

Related Questions