Seeking the value of a tab text using Selenium's web driver

Greetings! Currently, I am exploring the integration of selenium webdriver with mocha and node js in order to automate testing for a Single Page Application (SPA). My objective is simple - to locate a specific tab and perform a click action on it. The HTML content has been successfully loaded into the test environment. Below is a snippet of the code:

<div id="Tabs">
   <ul>
       <li> <span> one </span></li>
       <li> <span> two </span></li>
        ...
        <li> <span> six </span></li>
    </ul>
   </div>

Within my test.js file, the script is architected as follows:

describe("MYHtml",function(){
  var driver;
  var tabs;
  driver = new webdriver.Builder()
        .forBrowser('firefox')
        .build();
  driver.get("file:///home/myhtml.html");
  test.after(function() {
    driver.quit();
});

before(function(done){
    driver.findElement(By.id("Tabs")).then(function(e){
        e.findElements(By.tagName("li")).then(function(b){
            console.log("before got tabs length " + b.length);
            tabs=b;
            done();
         });
     });
});
test.it("we have some tabs",function(done){
    assert.strictEqual(tabs.length,6);
    console.log("we have tabs " + tabs.length);
    done();
});
test.it("can find a tab name",function(done){
    var span;
    for(var i=0;i<tabs.length;i++){
        tabs[i].findElements(By.tagName("span"))       
                    .then(function(span){
                        console.log("Field??" + span.getText());
                        //return span;
                        done();
                    });
    }
}); )};

While the test case "we have some tabs" passes without issues, the "can find a tab name" test case encounters an error as shown below:

1 failing

1) MYHtml can find tab name: TypeError: span.getText is not a function

The aim here is to search for a li element corresponding to the span text value of '2' so that a subsequent click operation can be executed.

Answer №1

Upon resolving the promise with "then," an array of span items is returned for processing. It is recommended to utilize getText() once the array has been returned:

tabs[i].findElements(By.tagName("span"))       
            .then(function(spanArray){
                console.log('Found spans length:'+ spanArray.length);
                spanArray.forEach(function(nextElement) {
                   nextElement.getText().then(function(text) {
                      console.log('Text Found' + text);
                      // An if then check is required here so only
                      // one done is called.
                      if (/*---your condition here ---*/) {
                          done();
                      }
                   });
                }); 
            });

MODIFICATION The code snippet above has been revised to handle arrays and process each element individually.

Additional Note Taking into account @sferret's suggestion concerning using XPATH for a more concise approach.

Alternatively, XPATH can be used to minimize code complexity and processing requirements:

var tab=driver.findElement(By.xpath(".//div[@id='Tabs']/ul/li/span[contains(.,'two')‌​]"));

However, caution must be exercised as XPATHs can introduce maintenance challenges if the location of elements like span or div changes frequently. It is important to anticipate potential page changes and adapt accordingly. Consider whether a small amount of additional JS code that remains stable over time is preferable to xPaths that may need frequent adjustments based on the layout changes.

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

Having trouble with Bootstrap v4 dropdown menu functionality?

For some reason, I cannot get the dropdown menu to work in my Bootstrap v4 implementation. I have tried copying and pasting the code directly from the documentation, as well as testing out examples from other sources on separate pages with no luck. &l ...

Secure user verification using session variable in the Express framework with NodeJs

Is it safe to use session variables for login persistence in the backend? What are the security implications and alternatives to consider? Technology Stack: Express (NodeJs) on the backend, MaterialUI (React) on the frontend I am seeking a straightforwa ...

ways to establish pathways for a function within express

My controller, var express = require('express'); var router = express.Router(); var mysql = require('mysql'); var connection = mysql.createConnection({ // connectionLimit : 100, //important host: 'localhost', user ...

Wait to fade in until the fade out process is completely finished

When I click on a button, the old box fades out and the new box fades in. However, I want to ensure that the .fadeIn() only happens once the .fadeOut() is complete. This will prevent two containers from being displayed simultaneously. Any suggestions on ...

There seems to be an issue with the server: Xt1.deprecate function is not defined

Currently, I am utilizing next.js version 13.4.12 with next-auth version 4.22.3 and prisma version 5.0.0, while also incorporating @next-auth/prisma-adapter version 1.0.7 in a TypeScript setup. Additionally, I have diligently followed all the necessary bo ...

Using PHP to reset variables for dynamic display in JavaScript

I've been working on retrieving values from a database and storing them in JavaScript variables. While I was successful in accomplishing this task, I encountered an issue when the values in the database are updated - the values of the variables remain ...

Help Needed: Adding a Simple Element to jQuery Tabs Script

I recently came across a fantastic jQuery tabs script on a website called Tutorialzine. The link to the article can be found here. As I was implementing this script, I realized I needed to customize it by adding specific classes to certain tabs. Specifica ...

What are the best methods for detecting devices in order to create customized CSS styles for iPad and Galaxy Tab?

Ensuring my web application is compatible with various devices is crucial. While I have created a common CSS for all mobile and tablet devices, it seems to be causing some problems specifically on the iPad. After finding a fix tailored for the iPad, I now ...

Identify the user's default character encoding in order to provide the appropriate CSV file

Is there a way for the website to automatically serve CSV files encoded as windows-1252 to users on Windows workstations, and encoded as UTF-8 to other users? Currently, two URL links are used which requires the user to decide which one to click. Most use ...

React - Incorrect components experiencing style changes due to setTimeout

Check out the code snippet here: https://jsfiddle.net/69z2wepo/204131/ A main component displays two 'notifications' each with different disappearance timings. class Page extends React.Component { constructor(props) { super(props); t ...

What could be the reason for the Javascript function failing to run?

I need assistance in executing a function called "send()" which includes an AJAX request. This function is located in ajax.js (included in the code snippet) The Ajax success updates the src attribute of my image. The function seems to be working correctly ...

Implementing a separate detail view in Vuejs

I am currently working on a page with multiple cases. When I click on a case, the details for that case appear on the same page. Here is a screenshot of how it looks: https://i.sstatic.net/Y9S4J.png As you can see in the screenshot, there are two cases li ...

Remove data from Firebase that is older than two hours

I need to implement a solution to automatically delete data that is older than two hours. Currently, I am iterating through all the data on the client-side and deleting outdated entries. However, this approach triggers the db.on('value') function ...

Guide on how to fill a jQuery DataTable with data from an XMLHttpRequest response

I have come across multiple inquiries on this topic, but none of the solutions provided have brought me close enough to resolving my issue. Hopefully, someone out there will find it simple to address. I am attempting to populate a DataTable using an XHR re ...

Steps to access an account using Selenium with Python

I am currently facing an issue with looping through a list extracted from an Excel sheet. I have saved this data for future use, but now I believe I need to utilize a for loop to iterate through the list and visit a specific website each time. The challe ...

Utilizing JSON API data to populate Leaflet maps

I am currently working on fetching JSON data from an API call, extracting the latitude, longitude, and name variables to create a GeoJSON array, and then displaying it on a Leaflet map. Despite not encountering any errors in the console, the geojson appea ...

Using HTML input checkboxes in conjunction with a JavaScript function

After creating a basic payment form using HTML/CSS/JS, I wanted to implement checks on user inputs using HTML patterns. In addition, I aimed to display a pop-up alert using JS to confirm the form submission only after all necessary inputs are correctly fil ...

Access the information from the text box and text area, then store it into a cookie using either jQuery or JavaScript

I need to save the text entered in a textbox within an iframe. How can I achieve this using jQuery or JavaScript? Any assistance would be greatly appreciated. ...

Switching a jQuery AJAX Response

Currently, I am utilizing an AJAX function to retrieve and display specific categorical posts when a corresponding button is clicked: <script> // Brochure AJAX function term_ajax_get(termID) { jQuery("#loading-animation").show(); ...

show a fresh new page using react router

I have recently developed a mobile app that showcases a collection of movies. Currently, it is static and I am looking to implement a react router for navigation. Specifically, I want the user to be directed to a detail page for a TV Show when they click o ...