简体   繁体   中英

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

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM