user1523236
user1523236

Reputation: 1463

clicking dynamic text using xpath and nightwatch.js

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

Upvotes: 2

Views: 3856

Answers (2)

MarkyMarksFunkyBunch
MarkyMarksFunkyBunch

Reputation: 1190

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

should be

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

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

Upvotes: 3

Florent B.
Florent B.

Reputation: 42518

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 + '")]')

Upvotes: 2

Related Questions