clicking dynamic text using xpath and nightwatch.js

两盒软妹~` 提交于 2019-12-11 00:17:20

问题


I wish to click on an element with dynamic text in my app. Generally to click on an element with text I do the following:

.useXpath().click("//*[contains(text(), 'some text')]")    

For my tests which have a dynamic name I try the following:

.useXpath().click("//*[contains(text(), "${name}")]")  

where name is a variable which contains the name of the newly created account. However when I try to run my tests I get the following:

.useXpath().click("//*[contains(text(), "${name}")]")
                    ^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: missing ) after argument list

Am I missing something? I don't see where I am missing the ). I have also tried various single/double quotes etc, but can't seem to get it working.

I have also attempted to use string concatenation as outlined here: (Passing a variable into an XPath expression in CasperJS), so my code looks like this:

 var selector = "\'//*[contains(text(), \'" + name + "\')]\'";
.useXpath().click(selector)

when I run the tests using this method I get the following:

ERROR: Unable to locate element: "'//*[contains(text(), '7ayhopt3ijhcwuo')]'" using: xpath

"7ayhopt3ijhcwuo" is the correct text to click on, but it does not seem to find it. Interestingly if I hard code the value like this:

.useXpath().click("//*[contains(text(), '7ayhopt3ijhcwuo')]") 

nightwatch is able to click on the text without any problems.

Any help on where I am going wrong with either method would be great! I am using node v7.8.0


回答1:


Either use a back-tick character around the string to embed the variable:

.useXpath().click(`//*[contains(text(), "${name}")]`)

Or use a combination of single and double quotes:

.useXpath().click('//*[contains(text(), "' + name + '")]')



回答2:


"\'//*[contains(text(), \'" + name + "\')]\'"

should be

"//*[contains(text(), '" + name + "')]"

You do not need to escape the single quotes inside of a double quoted string.



来源:https://stackoverflow.com/questions/44314715/clicking-dynamic-text-using-xpath-and-nightwatch-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!