Navigating through webdriverjs elements until a specific text value is found is a useful technique in test

Can anyone help me understand how looping in WebDriverJs works with promises?

Imagine you have the following html structure:

  <div id="textelements">
    <span onclick="spanClicked('Rock')">Rock</span>
    <span onclick="spanClicked('Paper')">Paper</span>
    <span onclick="spanClicked('Scissors')">Scissors</span>
  </div>

Using WebDriverJs, I want to locate the span containing the text 'Scissors' and click on it.

The ideal scenario would involve adding appropriate identifiers in the source HTML. However, if that is not an option, what would the WebDriverJs code look like for the given HTML structure?

I attempted the following approach:

function clickElementWithText(driver, textValue) {
    driver.findElements(webdriver.By.css('#textelements span')).then(function(spans) {
        for (var i = 0; i < spans.length; i++) {
            var matched = spans[i].getText().then(function(text) {
                console.log('Text value is: ' + text);
                return text === textValue;
            });
            console.log(matched);
            if (matched === true) {
                console.log('clicking!');
                spans[i].click();
                return;
            }
        }
    });
}

var webdriver = require('selenium-webdriver');
var driver = new webdriver.Builder().withCapabilities(webdriver.Capabilities.chrome()).build();
driver.get('http://webdriverjsdemo.github.io/');
clickElementWithText(driver, 'Scissors');

The issue arises when the variable matched does not evaluate to true as expected, even though it was supposed to be set as true.

Any insights into what might be causing this behavior?

Answer №1

Let's streamline the process using functional programming, specifically the filter() function:

var spans = driver.findElements(webdriver.By.css('#textelements span'));
webdriver.promise.filter(spans, function(span) {
    return span.getText().then(function(text) {
        console.log('Text value is: ' + text);
        return text === textValue;
    });
}).then(function (filteredSpans) {
    filteredSpans[0].click();
});

Alternatively, a more direct but less stylish approach would be to utilize By.xpath:

var span = driver.findElement(webdriver.By.xpath('//*[@id = "textelements"]//span[. = "' + textValue + '"]'));
span.click();

Another option is to verify the value of the onclick attribute with By.css:

var span = driver.findElement(webdriver.By.css('#textelements span[onclick*="' + textValue + '"]'));
span.click();

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

Automatically reveal or conceal an element based on the entry of a value in an input field, without relying on the keyup() or click events

I have a form field with a Bootstrap Datepicker that populates an <input> tag with a selected date. <div class="wrapper"> <div class="form-group"> <label>Select Date</label> <div class="input-group"> ...

The Intersection Observer encountered an issue as it was unable to access the property 'current' since it was undefined

My current project involves the implementation of IntersectionObserver, but I am facing an issue where I receive the error message Cannot read property 'current' of undefined. Can anyone help me identify what might be causing this problem? useOn ...

I'm having trouble persisting my mongoose model data in my MongoDB database

Hey there, I'm new to this and currently attempting to save the Amadeus object I've created into mongosh using the .save() method. However, after connecting to my file through node, editing the Amadeus object, and running amadeus.save(), I check ...

Tips for presenting hierarchical information from my database in ejs

I'm currently working on a genealogy application using node js express and ejs but I'm facing an issue with displaying the database in order (starting from parent). This is the code snippet for retrieving my data and what I see when I log the ou ...

jQuery not loading properly on the HTML page

I recently created an example.js file that utilizes jQuery. To include jQuery, I used the command npm install jquery and then added the script to my html file like this: <head> <script src="https://code.jquery.com/jquery-3.6.4.min.js"> ...

The Fetch function seems to be malfunctioning in Next.js

An issue has arisen while working with Next.js. The problem arises when attempting to fetch data from an API, an error message as seen here: consola, pops up unexpectedly. Despite deleting the database of the API, the error persists for some reason. Upon t ...

The custom server was functioning properly, but as soon as I altered the file directory, an error occurred on Next.js

After creating "create-next-app," I successfully set up the folder structure as follows: +client2 --.next --node_modules --public --... --server.js However, when I move my "server.js" file to a different location: +client2 --.next --no ...

Looking for a way to extract Regular Expressions from an IgGrid cell in Infragistics?

Is it possible to apply a regular expression to a igTextEditor within an igGrid Updating? I attempted to utilize the validate option, but it was unsuccessful. $("#schedulerTable").igGrid({ columns: $scope.schedulerColumns, widt ...

ObjectArray in Node.js

Building an object array in my node app involves transforming another object array. Let's assume the initial object array is structured like this... levels: [ { country_id: 356, country_name: "aaa", level0: "bbbb", level1: "cccc", level2: "dddd", le ...

Does an href and click events both happen simultaneously?

JavaScript Purpose: Implement a series of loops and create anchor links with the 'href' attribute <a class="mui-control-item" v-for="(item, index) in dai" v-on:click ="abc(item)" :href="'#item'+(index+1)+ 'mobile'" ...

maximum number of results in google custom search limit

I'm trying to retrieve the top 40 results from the Google API, but when I limit the result using the code below, it doesn't seem to work. How can I achieve getting the top 40 results with the Google API? <script> (function() { ...

Encountering an error when trying to destructure a property of null

The concept of destructuring is fascinating, but I have been facing some challenges when trying to destructure nested objects. Consider the following code snippet: const { credit: { amount }, } = userProfile This can be risky because if the &ap ...

When combining Socket.io 1.0 with express 4.2, the outcome is a lack of socket connection

According to the title, I am attempting to integrate socket.io 1.0.4 with express 4.2, but all requests with "/?EIO" are resulting in a 404 error. Below are my file configurations: ./bin/www : #!/usr/bin/env node var debug = require('debug')(& ...

Tips for transferring data between two forms in separate iFrames

I'm trying to achieve a functionality where the data entered in one form can be submitted to another form within an iframe. The idea is to allow visitors to preview their selected car in the iframe, and if satisfied, simply press save on the first for ...

Activate the Giphy search feature in the Slack Nestor bot's response

How can the nestor bot be configured to use a giphy search when replying in a Slack channel where the giphy plugin is active? Can something like msg.reply('/giphy ' + text, done); be used for this purpose? ...

JavaScript challenge: Create a group of buttons with the same class name that, when pressed once, will trigger changes in all of them simultaneously

Hey there, I could really use some assistance with an issue I've been grappling with for the past three days. I'm fairly new to wordpress-woocommerce and php, and I'm encountering a problem with my theme. It doesn't display any indicati ...

What is the most effective method for incorporating multi-line breadcrumb links in a React application?

I am currently working on implementing a multiline breadcrumb link feature for mobile and tablet devices. As users navigate through multiple folders, I need to handle scenarios where the number of links exceeds the maximum allowed in the breadcrumb contain ...

When attempting to develop a discord bot using Heroku, I encounter an issue where the bot functions properly when run locally, but malfunctions once deployed on Heroku's platform

After successfully running index.js locally, I encountered an error upon trying to deploy the code on Heroku. The specific error received was: 2022-01-11T05:25:24.034595+00:00 app[worker.1]: at Module._compile (node:internal/modules/cjs/loader:1101 ...

The intricacies of how Node.js handles asynchronous execution flow

I wanted to ask about the best approach for displaying data retrieved from MySQL. Do you think this workflow is correct? app.get('/demo/:id', function(req, res) { var query = csql.query('SELECT * FROM table_videos WHERE id=? LIMIT 1' ...

Display a loading screen with a progress bar using React Native Expo

Currently, I am diving into the world of React Native and honing my skills using Expo. One of the tasks I've tackled is creating a loading screen for my app using npm react-native-progress. However, I'm curious if there is a way to replace the de ...