Developing numerous test suites within Selenium WebDriver

I am working on a testing script using selenium webdriver, phantomJS, and Mocha.

My scripts are written in JavaScript.

These are the variables declared outside the test modules:

var afterLoginURL;
var afterLoginTitle;
var loginFlag = 0;

I have two test modules:

test.describe('Site Login Test', function() 
{
    test.it('User Login', function() 
    {
        var driver = new webdriver.Builder()
                    .withCapabilities(webdriver.Capabilities.phantomjs())
                    .build();
        driver.get(baseUrl);
        driver.getTitle().then(function(title) 
        {
            if(expectedTitle === title) /* if the title matches */
            {
                driver.findElement(By.id('username')).sendKeys(username); 
                driver.findElement(By.id('password')).sendKeys(password);
                driver.findElement(By.id('_submit')).click();

                if(username.length > 0 && password.length > 0)
                {
                    driver.findElements(By.xpath("//a[contains(text(), 'Log out')]")).then(function(elem)
                    {
                        if(elem.length > 0)
                             loginFlag = 1;
                        else
                             console.log("Login Unsuccessful");
                        if(loginFlag == 1)
                        {
                            console.log("Login Successful");
                            // after login, we are in the dashboard page, counting a side menu <li> //
                            driver.findElements(By.xpath("//ul[contains(@id, 'sidemenu')]/li")).then(function(liSize)
                            {
                                console.log(liSize);
                            });
                            driver.getCurrentUrl().then(function(url){
                                afterLoginURL = url;
                            });
                            driver.getTitle().then(function(title){
                                afterLoginTitle =  title;
                            });
                        }
                        else
                        {
                            console.log("Login Unsuccessful");
                        }   
                    });
                }
            }
            else    /* if the title doesn't match */
            {
                console.log("Verification Failed - An incorrect title.");
            }
        });
    });
});

In the next test module, I navigate directly to the dashboard page and check for elements within the <ul> and <li>, but encounter an error locating the element:

test.describe('Menu Test', function() 
{
    test.it('Detect Menu', function() 
    {
        var driver = new webdriver.Builder()
                        .withCapabilities(webdriver.Capabilities.phantomjs())
                        .build();
        if(loginFlag == 1)
        {
            console.log("afterLoginURL :" +afterLoginURL);
            console.log("afterLoginTitle :" +afterLoginTitle);
            driver.get(afterLoginURL);    
            driver.getTitle().then(function(title) 
            {
                if(afterLoginTitle === title)
                {
                    console.log("Visited After Login Page");

                    driver.findElement(By.xpath("//ul[contains(@id, 'sidemenu')]/li")).then(function(elem){
                    console.log(elem.length);
                    // getting error in this section;
                    });
                }
                else
                {
                    console.log("Something wrong has happened. Much bigger than calamity");
                }
            });
        }
        else
        {
            console.log("Not logged in");
        }
        driver.quit();
    });
});

This is the error message being displayed:

NoSuchElementError: {"errorMessage":"Unable to find element with xpath 
'//ul[contains(@id, 'sidemenu')]/li'"

What could be the issue here?

Is it because the session expired? How can I revisit the dashboard page (in another test module) without facing session expiry to detect the menu?

Here is the HTML structure:

<ul class="nav nav-second-level collapse" id="sidemenu">
        <li>
        <a href="/admin/user/">All Users</a>
        </li>
        <li>
        <a href="/admin/company/">All Companies</a>
        </li>
        <li>
        <a href="/admin/device/">Devices</a>
        </li>
        <li>
        <a href="/admin/email/">Send Email</a>
        </li>
        <li>
        <a href="/admin/impersonate">Impersonate User</a>
        </li>
        <li>
        <a href="/admin/encrypttest">Test Encryption</a>
        </li>
    </ul>

Answer №1

Have you considered utilizing a CSS selector for this task?

driver.findElement(By.cssSelector("#sidemenu > li")).then(function(element){
                console.log(element.length);
                // encountering an issue in this particular section;
                });

The specified CSS selector is searching for an element with the ID (#) sidemenu that contains child elements LI. Based on the HTML provided, there are multiple instances of such elements.

Additionally, what is the intended outcome of element.length? Were you possibly intending to use .findElementS() instead to print the number of elements located?

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

In Safari, the scrollbar appears on top of any overlays, popups, and modals

On my webpage, I have a div with the CSS property overflow-y: scroll. The page also features several popup modals and overlays. Strangely, the scrollbar of the div appears on top of these overlays instead of behind them. I attempted to resolve this issue b ...

Create an event listener for clicking on an image that potentially has a corner ribbon obscuring a portion of it

In my project, there is a div element with an id of items containing several bootstrap cards. Each card includes an image tag and some are accompanied by the following HTML code: <div class="ribbon"><span>Sale</span></div> This co ...

Rearrange the order of elements within an array and move elements around within it

I am looking to select an element from an array, relocate it to a different index, and then shift the elements in-between by 1 position. Consider this as drag-and-drop functionality, where if the starting index (from) is less than the destination index ( ...

Implementing a change event upon setting a value to an input element using JavaScript

My plan is to develop a Chrome extension that can automatically fill passwords. The code for this functionality looks like the following: //get the account document.querySelector("input[type=text]").addEventListener('input', () => { ...

Transferring PHP Array information to JavaScript

I'm facing an issue with transferring data from a PHP function querying a mySQL database to a JavaScript function for use in a plotly graph. Although I can successfully retrieve the data in PHP, I encounter a problem when trying to access it in my Jav ...

Verifying for an empty req.body does not function as expected within Express

I was experimenting with testing my login request in Postman using an empty body and encountered an issue. For some reason, the check for an empty body didn't work as expected and the code execution continued even when the body was empty. What could b ...

Troubleshooting Problem with Bootstrap 4 Navigation Drop-Down Menu

I am working on developing some navigation forms for my university projects. I encountered an issue where I selected the Book item, and the navigation was working fine. However, when I selected Child items and then clicked on the Organization item, the nav ...

Dealing with errors when chaining promises in a react-redux application

This is related to a question asked on Stack Overflow about Handling async errors in a react redux application In my react-redux setup, I am facing a scenario where I need to chain multiple API calls upon successful completion of each. How can I achieve ...

Cufon: Hovering on links causes them to resize and remain in that new size

I've encountered an issue with text links in a paragraph that are being replaced using Cufon. When I hover over the links, the text inside them expands and remains that way even after moving the cursor away. The color change applied to the hover state ...

Encountering an issue with React where the useContext hook is returning undefined instead of

I am facing an issue where I am attempting to access state and setState from the Store file, but it returns as undefined. Can someone help me understand what is causing this problem and how I can resolve it? import React, {createContext, useState} from &ap ...

What is the best way to showcase images using Vue.js?

For my Vue project, I am encountering issues with the image paths not working properly. Despite trying different variations, such as: <figure class="workout-image"> <img :src= "images.bicep" width= "200px" ...

JavaScript: Show Loading Screen until certain assets are fully loaded

Just a quick overview. I currently have a loading screen that appears before the website finishes loading for a specified time. What I'm looking to achieve is a method to check if certain elements are loaded and then remove the loading screen, rathe ...

What is the purpose of the <React.StrictMode></React.StrictMode> component in React?

I stumbled upon this code snippet while practicing React, and I'm curious about its functionality. For example: const App = () => { return ( <React.StrictMode> <div id="cool-attribute"> <h1>Welcome to the Jun ...

sending XML data through Google Maps API V3

While working on integrating the google maps api v3, I encountered an issue when trying to pass an XML file to populate the map with results. Upon checking the PHP file responsible for generating the XML data, everything seems to be in order. The PHP file ...

Enhance a DOM element using personalized functions in jQuery

Seeking advice on how to create custom widget placeholders with a "setvalue" function specific to each type of widget: $.fn.extend($(".dial"), { setval: function(val) { }); Attempting to avoid extending jQuery.fn directly since different widget type ...

Troubleshooting Vue.js: Understanding the Issue with Debonuce Function and Arrow Functions

Here is a custom debounce function I implemented: function customDebounce(func, delay = 1500) { let timeout; return function (...args) { if (timeout) clearTimeout(timeout); let context = this; timeout = setTimeout(function () { func.a ...

Navigate quickly to a CSS selector in a CSS file directly from an HTML file in Vim with just one keystroke

After reviewing the information I found on Jump to CSS definition when editing HTML in VIM, it unfortunately did not provide the answer I was looking for. I am interested in being able to easily navigate to the CSS or JavaScript code from an HTML file. Id ...

Inconsistencies in Height Among JQuery Elements

I am encountering an issue with my datatable.js, where I am attempting to limit its height based on a specific row number, such as 4.5 rows. However, I am facing a problem with the row height (tr height). For example, when using the following method with m ...

What is the best way to change this date format into a JavaScript Date object?

Dealing with a service that gives me a strange date format, and I'm struggling to find a simple way to convert it into a JS Date Object. I have some important logic to implement with these dates, so converting them is crucial. The date format provide ...

Invoking Node to utilize React/Webpack module code

Trying to figure out how to integrate client-side import/export modules into a Node.js require script within my custom NextJS webpack config: module.exports = { webpack: (config, options) => { if (options.isServer) { require("./some-scr ...