Using Selenium together with Mocha/Chai to determine the absence of an item in the DOM and return false

In my current project, I am using selenium-webdriver with Mocha & Chai in a JavaScript environment. I am trying to determine if a user is logged in by checking for the presence of a specific element in the DOM.

If the user is logged in, then the following element exists:

<a class="account-panel-controls__link" role="link" id="sign-out-nav" data-log-out="">Sign out</a>

I need to find this element and click on it if present. If not, I want to click on another element that only appears when the previous one is absent:

<a class="account-panel-controls__link" role="link" id="registration-sign-in-nav" data-log-out="">Sign in</a>

I have tried various approaches, but none seem to work reliably. The code I currently have works fine when the element with Id 'sign-out-nav' is initially present, but fails if it is not found, resulting in a test failure due to being unable to locate the element in the DOM at all.

driver.findElement(By.id('sign-out-nav')).isDisplayed().then(function (displayed) {
    if (displayed) {
        driver.findElement(By.id('sign-out-nav')).click();
    }
    else{
        driver.findElement(By.id('registration-sign-in-nav')).click();
    }
});

I have searched through multiple resources, attempting solutions such as .getSize() and checking for length, but I cannot get any of those methods to work. Using 'findElements' along with .length also returns an [Object object] value with a length of 1, making it difficult to distinguish the values.

Is there something crucial that I am overlooking?

Thank you

Answer №1

In my experience, I have found that utilizing a combination of webdriverio, mocha, assertjs, and selenium can be quite helpful. For example:

assert.doesNotThrow(() => { browser.getText('#registration-sign-in-nav') });

This particular approach has proven effective for the technology stack I am currently working with. The code above is useful because it handles scenarios where the specified element is not present, resulting in an error being thrown.

Answer №2

When searching for elements on a webpage, it is best practice to utilize the .findElements() method:

// example of finding an element on the page:
driver.findElements(By.id('sign-out-nav')) .then(found => console.log('Element found? %s', !!found.length));

If the .length > 0, then the element has been located. You can proceed with using .elementIsVisible() and .elementIsEnabled() for further validation before performing clicks or other actions as needed.

Remember to consider using indexes if multiple elements are found, either within the .findElement() method if only one element needs to be selected.

Answer №3

Working with Selenium can be quite tricky, especially when trying to locate page elements. One trick is to wrap your driver.findElement method with a driver.wait() function and see if that helps in locating the element successfully.

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

There is no way to avoid a PHP variable being displayed in a JavaScript alert box

It may sound silly, but I've spent hours trying to escape this PHP variable that contains post data: $post=array ( 'offers' => '90', 'pn' => '2', 'ord' => 'price', 'category_s ...

Tips on incorporating a hyperlink into an object imported through GLTF loader

Is there a way to include a hyperlink in the object loaded using gltf loader with the given code snippet below? var loader = new THREE.GLTFLoader(); var mesh; loader.load('globe.glb', function(gltf){ console.log(gltf); me ...

Encountering an issue with Masonry's container.append that is causing an Uncaught TypeError: Object does not possess the filter method

I have implemented infinite scroll on my website to display images. The images are arranged using a tool called masonry. Initially, I only load 10 images into the #container div when the page loads. These images are aligned perfectly with no errors in the ...

Every time I try to loop through my JSON object using an $.each statement, an error is thrown

When I execute an $.each loop on my json object, I encounter an error 'Uncaught TypeError: Cannot read property 'length' of undefined'. It seems that the issue lies within the $.each loop as commenting it out results in the console.log ...

Issues arise when trying to use a JavaScript function within an HTML form, with an error message stating "TypeError: total

Recently, I encountered an issue with a straightforward JavaScript function that calculates user input. The function performed as expected when I tested it without the form tag. However, when I tried using the same code within the form tag, an error was di ...

The constructor for audio in Next JS cannot be found

I'm facing an issue and struggling to find a solution. My project follows the standard structure of Next JS. In the root directory, I have included a components folder. Within the components folder, there is a component with the following code: imp ...

Ways to stop Google Places API from generating outcomes from a particular country

After carefully reviewing the entire documentation at https://developers.google.com/maps/documentation/javascript/reference/places-service#LocationRestriction, I am still unable to find a solution to my problem. I have successfully limited Google autocomp ...

Convert JavaScript objects to strings with JSON strings already included as values

Although this question may seem like a duplicate, I have not been able to find the answer. My issue is with stringifying a JavaScript object that contains JSON strings as values. Here is an example: var obj = {id:1, options:"{\"code\":3,\" ...

Tips for programmatically relocating the slider handle in HTML 5 range input without relying on Jquery UI

INQUIRY: I am facing an issue with an HTML5 range input slider in my project. When I try to change the value of the slider using jQuery, the handle's position remains unchanged. While I am aware that this can be resolved using the .slider() method in ...

Utilizing Python Selenium to implement CPU throttling in Chrome

Can CPU throttling be controlled in Chrome's devtools using Python Selenium? If yes, what is the method to do so? I noticed that the driver has a method called execute_cdp_cmd, which stands for "Execute Chrome Devtools Protocol command", but I am uns ...

Tips for applying textures dynamically to MeshPhongMaterial?

When trying to apply a texture on a THREE.MeshPhongMaterial, the texture fails to load. Here's the code snippet: let earth_geometry = new THREE.SphereGeometry(450, 10, 10) let earth_material = new THREE.MeshPhongMaterial({ emissive: 0xffffff }) ...

Next.js project encountered a TypeError with message [ERR_INVALID_ARG_TYPE]: The "to" argument is expected to be a string type

While working on a Next.js application, I came across a TypeError that is linked to the undefined "to" argument. This issue pops up when I launch my development server using npm run dev. Despite checking my environment setup and project dependencies, I hav ...

Creating a polygon path in Google Maps v3 using an array of coordinates

I'm currently working on creating a polygon around US counties. The coordinates for this polygon are coming from a database and then being json encoded for use in JavaScript. Below is the JSON encoded array generated from PHP code: {"Abbeville-sc":[[ ...

Issue with retrieving URL parameters in Nextjs during server side rendering

Currently, I'm attempting to extract the request query, also known as GET parameters, from the URL in server-side rendering for validation and authentication purposes, such as with a Shopify shop. However, I am facing issues with verifying or parsing ...

implementing AJAX functionality in Laravel when a drop-down item is selected

Hello there, I am a newcomer to the world of coding and I'm currently learning Laravel for a personal project. My goal is to retrieve data from a database based on the selection made in a dropdown menu. Here's the code for the dropdown menu: < ...

Utilizing Node as an intermediary to transmit form-data to a Java server

I am working on an application that utilizes axios for communication with a node server, which then interacts with a separate java server. Calling the node server from the client: // assuming payload is of type FormData() axios.post(url, payload).then((r ...

Tips for resolving rendering page issues in an express app

My application is a straightforward blog platform that showcases a schema for the title, entry, and date of each blog post. There is also an edit/delete feature that is currently under development. When attempting to use the edit/delete button on a selecte ...

We are sorry, but the requested route cannot be located

I'm diving into the world of express and trying to set up subroutes for a specific "plan" with corresponding actions. My journey begins at mypage.com/someroute/123321312 router.get('/:planId', function(req, res, next) { //a form is render ...

What is the best way to extract the refresh token from the headers while utilizing node.js?

I currently have two tokens, an accesstoken and a refreshtoken, in the authorization section. The accesstoken is located in the front while the refreshtoken is in the back. I successfully obtained the accesstoken, but now I need to filter out the refresht ...

Problems encountered when trying to deploy on Firebase

I've been working on deploying my web app to Firebase, and I successfully ran the deploy script. However, when I try to access the URL, instead of seeing my app, I'm greeted with the Open Hosting Documentation page. Here is what my firebase.json ...