2

I used this string to find an element:

cy.xpath('//*[text()="search ${keyword}")]')

And when I run my test, it shows me the right result in console but also it shows me this error:

Failed to execute 'evaluate' on 'Document': The string '//*[text()="search ${keyword}")]' is not a valid XPath expression.

kjhughes
  • 106,133
  • 27
  • 181
  • 240

2 Answers2

1

I used contains and it works. there is an icon in my XPath and it couldn't find just the text.

cy.xpath(`//*[contains(text(), 'search ${keyword}')]`)
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Ethan Jun 11 '22 at 15:00
0

Issue with your original question

The actual syntax error is due to an extraneous ):

cy.xpath('//*[text()="search ${keyword}")]')
                                        ^

Delete that character to eliminate the syntax error.

Issue with your self-answer

Your solution,

cy.xpath(`//*[contains(text(), 'search ${keyword}')]`)

doesn't do what you likely think it does. (It's only checking for substrings within the first text() node child of every element.) For full details, see this extensive explanation.

Instead, use

cy.xpath(`//*[text()[contains(., 'search ${keyword}')]]`)

or the other variation shown in the linked explanation per your requirements.

kjhughes
  • 106,133
  • 27
  • 181
  • 240