Utilizing XPath and nightwatch.js to interact with dynamic text elements with a simple click

When trying to click on an element with dynamic text in my app, I encounter a syntax error. Normally, to select an element by its text, I use the following format:

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

But for elements with dynamic names, I attempt the following approach:

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

The variable "name" holds the name of the newly created account. However, when I run my tests, I face the following issue:

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

I have tried different combinations of single and double quotes but haven't been successful. I also explored string concatenation as suggested in this discussion: (Passing a variable into an XPath expression in CasperJS), which led me to modify my code like this:

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

Unfortunately, when I implement this method, I receive the following error message:

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

The text '7ayhopt3ijhcwuo' is the correct target, but it cannot be found. Interestingly, if I hard code the value like so:

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

nightwatch successfully clicks on the desired text without any issues.

If anyone can provide guidance on how to resolve these methods, I would greatly appreciate it! My environment uses node v7.8.0

Answer №1

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

should transform into

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

No need to escape single quotes within double quotes.

Answer №2

To include the variable in the string, you can either enclose it with back-tick characters:

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

Alternatively, you can mix single and double quotes:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using async/await with recursion in NodeJS for handling express requests

My code contains a function named GetAllData() that triggers the GetPurchaseData function, which in turn calls itself recursively until all the data is loaded. async function GetAllData(){ console.log("starting loading purchase data"); await G ...

Facilitating the integration of both Typescript and JavaScript within a Node application

We are currently integrating Typescript into an existing node project written in JS to facilitate ongoing refactoring efforts. To enable Typescript, I have included a tsConfig with the following configuration: { "compilerOptions": { "target": "es6", ...

How can I activate, pause, or continue using chrome devtools?

Preq: To begin, the selenium script in python must be launched. After launching, the next step involves connecting to chrome devtools to control script execution for debugging purposes. Upon starting the selenium script playback, it retrieves the websocke ...

Discover local points of interest with the Google Places API integration on your WordPress site through PHP programming

$(document).ready(function() { var image_src = "images/"; var map; var infowindow; var bounds = new google.maps.LatLngBounds(); var PlaceArray = ["restaurant", "cafe", "bar", "grocery_or_supermarket", "parks", "school", "shopping_mall", "movie_t ...

Choose the parent element within an Angular application

I need help selecting the parent element (searchres) in Angular and applying styles to it. Here is my HTML code: <div ng-repeat="product in products" class="searchres"> <a href="#"> <img src="{{product.path}}" cla ...

Issue with table display within <div> element in React

Recently diving into React, I find myself in a situation where I need to display data in a table once it's ready or show 'Loading' if not. Currently, my render() function looks like this: return ( <div> { this.state.loaded ...

Error: Cannot access collection property of dbObject

I've been working on fetching data from a database, but I've hit a roadblock. I keep encountering an error and can't seem to figure out what's causing it. I've searched for solutions but haven't found one that works yet. I&apo ...

Update the value of a scope variable directly within a controller. Subsequently making a function call

Hey there, I just want to start by saying sorry in case this question has already been asked or if it seems silly. I'm pretty new to AngularJS and have managed to overcome CORS errors, set up login via Parse, and even created an API for my app using ...

Error encountered during the prerendering process on Vercel's Next.js build

While trying to compile my website on Vercel, I encountered a pre-rendering error during export. Does anyone know why this is happening and can provide assistance? Here is the link to my GitHub repository where all the code is stored: https://github.com/M ...

Integrate these scripts for seamless functionality: JavaScript/AJAX and PHP

Currently, I am in the process of learning all the languages involved here and facing a challenge while trying to merge two scripts to perform a single task. The goal is to select a branch from a form option list, transmit that value from the option to a ...

Creating a Jest mock for Sendgrid in the __mocks__ directory

Here's my sendgrid code located in the __mocks__ directory: class MailService {} const mail = jest.fn( () => (MailService.prototype = { setApiKey: jest.fn(), send: jest.fn(), }) ); module.exports = mail; module.exports.MailS ...

Interactive image rotator featuring navigation buttons for next and previous slides

I recently followed a tutorial from W3Schools Now, I am looking to enhance it by adding previous / next buttons for the indicators, rather than for the slider itself Here is what I aim to accomplish: https://i.sstatic.net/qH1PQ.png Below is the code sn ...

Ensure that the form is submitted when a checkbox is clicked, while also maintaining the native browser

My form contains a text input field and a checkbox. The text input must not be left empty when the form is submitted, which is why the required attribute is used. I want the form to be submitted every time the checkbox is clicked, while still maintaining ...

Navigating Firefox on Windows with Selenium-RC from a Linux operating system

Currently, I am utilizing phpunit version 3.4.15 for my testing needs. In order to run Selenium tests on Centos 5.3 Linux, I have initiated Selenium server 1.0.3 by using the command: java -jar selenium-server.jar My objective is to trigger a browser tha ...

Troubleshooting jQuery Sortable Issue with Table and Row Width in ASP.NET MVC View

I am facing an issue with jQuery UI sortable while trying to make my table grid sortable. Despite not getting any error messages, the sortable function is not working as expected. I have never utilized this method in a MVC (views/razor) project before. An ...

What is the best way to elegantly transition an element with Hammer.js and JQuery?

As I work on developing a versatile web application meant for use on computers, tablets, and possibly smartphones, I've encountered a design challenge with the menus. Currently, the menus are laid out horizontally on one page, allowing users to swipe ...

The functionality of JQuery stops functioning once ajax (Node.js, PUG) is integrated

I've been attempting to incorporate a like feature on my blog post website. When I click on the likes count, it's supposed to trigger an ajax call. In my server.js file, there's a function that handles the POST request to update the number ...

Challenges encountered while using Selenium WebDriver to upload images

I'm having trouble adding an image as a normal attachment to an email (not as an inline image). When inspecting the HTML DOM with Firebug, I noticed there are two elements with xpath //input@type='file', which is due to the presence of two b ...

Dynamic image updates in real-time

Beginning a new project and already facing a roadblock, I could really use some assistance. I have 16 (4x4) images that I am displaying on a page. $max_images = $_GET['images']; $num_images = $max_images; while (($num_images > 0) && ...

Difficulty comprehending the response from an AJAX post is being experienced

I'm currently working on a website and facing an issue connecting JavaScript with PHP using AJAX. Specifically, I'm struggling with reading the AJAX response. My PHP script contains the following code: <?php echo "1"; In addition, I have a ...