Home > Net >  How to solve "not a valid XPath expression" error in Cypress?
How to solve "not a valid XPath expression" error in Cypress?

Time:06-12

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.

CodePudding user response:

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

CodePudding user response:

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.

  • Related