Reputation:
I have a XPath selector in my tests like this, which I copied directly from the dev tools in Chrome:
//*[@data-testid='menu-item']//strong[text()='Link for Image']
It works in the browser, but when I try to use this in my tests, I get this error message:
SyntaxError: Document.evaluate: The expression is not a legal expression
I think it's the last half of the selector that's having issues, but I'm not sure what is syntactically wrong...
Upvotes: 1
Views: 1665
Reputation: 111726
//*[@data-testid='menu-item']//strong[text()='Link for Image']
is a syntactically correct XPath expression.
Be sure to use double quotes as delimiters given that you're using single quotes within the XPath:
"//*[@data-testid='menu-item']//strong[text()='Link for Image']"
So, for example, if you're calling document.evaluate()
in JavaScript, it would be
document.evaluate("//*[@data-testid='menu-item']//strong[text()='Link for Image']",
document)
Update after OP's comment:
Oh! My mistake, it's not a string in the xpath, it's a string interpolation! That seems to be why...
//*[@data-testid='menu-item']//strong[text()=${USER_STRING}]
So, in addition to the previously mentioned single/double quote concern for the entire XPath, you'll want to pay attention to whether ${USER_STRING}
itself has quotes, and what type they are. If it has no quotes, then be sure to delimit the variable with them:
//*[@data-testid='menu-item']//strong[text()='${USER_STRING}']
And of course, you'll need to make sure that ${USER_STRING}
is actually being evaluated/substituted ahead of the function call expecting a well-formed XPath expression.
Finally, if ${USER_STRING}
comes from an unsecured source, be sure to sanitize before evaluating.
Upvotes: 1