Search code examples
typescriptplaywright

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


Solution

  • 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}')`)