Dealing with hidden elements poses a challenge for Selenium as it struggles to catch ElementNotVisibleException

Currently, I am working on creating user interface tests using selenium and I came across a method that is supposed to handle non-existing elements and hidden elements.

The issue arises in the second catch block where the method consistently returns 'true' even when the element is not displayed or hidden (visibility: hidden).

public boolean checkElementPresence(By locator, WebDriver driver) {
    WebElement element = null;
    try {
        element = this.findElement(locator, 10, driver);
    } catch (TimeoutException te) {
        System.out.println("Timeout - This element could not be found: " + locator.toString());
        return false;
    } 
    catch (ElementNotVisibleException env) {
        System.out.println("This element was found but is not visible: " + locator.toString());
        return false;
    }
    if (element == null ) {
        return false;
    } else {
        return true;
    }
}

public WebElement findElement(By locator, int timeout, WebDriver driver) {
    System.out.println("Calling findElement method: " + locator.toString());
    int interval = 5;
    if (timeout <= 20)
        interval = 3;
    if (timeout <= 10)
        interval = 2;
    if (timeout <= 4)
        interval = 1;
    Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
            .withTimeout(timeout, TimeUnit.SECONDS)
            .pollingEvery(interval, TimeUnit.SECONDS)
            .ignoring(NoSuchElementException.class, StaleElementReferenceException.class);
    WebElement webElement = wait.until(ExpectedConditions.presenceOfElementLocated(locator));
    return webElement;
}

If anyone has suggestions on how to modify this code to detect hidden existing elements, I would greatly appreciate it. Thank you!

Answer №1

Checking for the presence of an element in the DOM is essential, but it doesn't guarantee visibility.

Instead of just checking for presence, consider using visibilityOfElementLocated to ensure that the element is both present and visible on the page. Visibility implies that the element not only exists but also has a size greater than 0.

For more information, refer to this resource.

If you encounter ElementNotVisibleException, it might indicate that the element is hidden when interacting with it. This exception is typically thrown during interaction, not lookup.</p>

<p>Simplify your code by using this function:</p>

<pre><code>public boolean elementExists(By locator, WebDriver driver){
    return  (new WebDriverWait(driver, 60)
            .ignoring(NoSuchElementException.class)
            .ignoring(StaleElementReferenceException.class)
            .until(ExpectedConditions.visibilityOfElementLocated(locator))) != null;
}

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

Effective time management in Selenium scripts: Running the same script on multiple servers

I've been working on automating the functionality of my web project. I've successfully created a test suite using Selenium WebDriver that works perfectly fine on my local server. However, when I tried to execute the same test suite on an Azure se ...

Receiving a "Bad Request" error when trying to access a website

Every time I attempt to call a lengthy URL, I encounter a Bad Request issue. https://localhost:44320/RespostaEmail/96635/750396/[%7B%22IdItem%22:8,%22IdTipoReposta%22:80%7D,%7B%22IdItem%22:1,%22IdTipoReposta%22:80%7D,%7B%22IdItem%22:3,%22IdTipoReposta%22:8 ...

What is the best way to determine if an image has successfully loaded in Codeception tests?

I need to verify whether the Verisign logo images are loading correctly $I->seeElement('DIV#security IMG.verisign'); However, my current test is passing even when the image is not loaded (e.g. for a 404 error if the file name of the source i ...

Why is the JavaScript function working even without any arguments?

During my search for some JS Code, I stumbled upon this piece of code. Check out the code snippet below: arg = "TEST ALERT MESSAGE"; MyFunction(arg); function MyFunction() { alert(arg) } In the above code snippet, the MyFunction() is provided with an a ...

What is the best way to extract all query parameters in React-Router-DOM v6 using `useSearchParams` without having to specify the key?

I'm currently developing a React project using react-router-dom v6 and my goal is to extract all query parameters. http://localhost:3000/users?page=5&pageSize=25 The specific query parameters I am looking for are page and pageSize. I am aware of ...

Ways to deselect checkboxes and eliminate validation requirements

Below is the HTML code snippet that I am working with: <div class="form-group"> <div class="input-group"> <label for="daterange-vacancy" class="input-group-addon">Van</label> ...

Using jQuery AJAX for uploading multiple files, each file is sent to the server one at a time using the AJAX method

Here is the HTML code snippet that I am currently working with: <form id="submit-form"> <input type="file" id="resume" name="resume[]" class="inputFileHidden" multiple> <input type="submit"> </form> My goal ...

Trying out a function named on Sinon.js spy

Currently, I am utilizing SinonJS to verify that my controller is calling certain methods within my view. Specifically, I am aiming to confirm that the addSeat method is invoked with the value of testSeat. Despite my efforts in the code snippet below, I am ...

Ways to automatically refresh a page in Javascript after a short period of user inactivity

Similar Question: How Can I Modify This Code To Redirect Only When There Is No Mouse Movement I am looking to update a web page automatically if the user is inactive, specifically through key presses or mouse clicks using Javascript. ...

How can I make a bootstrap offcanvas disappear in Vue 3 after clicking a router-link?

Hey there! I'm looking to close the bootstrap-5 Offcanvas when I click on a link inside it. Here's the code for the Offcanvas: //Button activate Offcanvas <button class="navbar-toggler" type="button" data-bs-toggle=&quo ...

Need to import a custom module using npm and TypeScript

Exploring two projects: main-project and lib-project, both written in TypeScript and compiled to common JavaScript using gulp. Our objective is to require lib-project in main-project. lib-project |-- package.json |-- gulpfile.js |-- dist |-- index.js ...

exploring asynchronous javascript behavior utilizing the sleep/setTimeout function in the context of THREEJS and Angular

As a newcomer to Javascript and asynchronous programming, I am facing what I believe to be a beginner's issue. I have been using ThreeJS to create a scene with multiple objects (approximately 100) and everything was working smoothly until now. My cu ...

Obtaining the data stored in objects within a parse database

I'm currently facing an issue where I am trying to retrieve the name of the creator from the session object, which is a pointer. For testing purposes, I have been attempting to access this information but it keeps showing up as undefined. Any suggesti ...

Exploring the possibilities of page manipulation using React Native WebView

I'm encountering an issue with my implementation of react-native-webview. When I use it to open a webpage, the audio doesn't start playing automatically. Instead, I have to press a button for it to play. Is there a way to make the audio play dire ...

If the array in a React FOR loop changes but some of the keys remain the same, will all the components rerender?

I'm currently working on incorporating infinite scroll functionality for a series of videos. To differentiate each component, I am utilizing a unique identifier as the key. Given that each component will be quite sizable, my goal is to only display a ...

"Fixing the issue of an undefined option being added to

In my controller, I have defined an object called tempScale: $scope.tempScale = { scaleType : [], deviations : [], intervals : 0 }; This object is connected to the HTML through this code: <select id="scales" ng-model="tempScale.scaleType" ...

How to achieve the functionality of multiple inheritance using Object.create()

Seeking insights on implementing multiple inheritance in JavaScript. Various methods exist, each with pros and cons. However, there lacks a comprehensive analysis of Object.create() presented in an understandable manner. After conducting experiments, I hav ...

Creating a jQuery accordion: A step-by-step guide

I'm currently working on building a dynamic accordion using jQuery where only one element can be open at a time. When a new element is opened, the previous one should close. I've managed to make it open and hide the button when opening it, but I ...

React SVG not displaying on page

I am facing an issue with displaying an SVG in my React application. Below is the code snippet: <svg className="svg-arrow"> <use xlinkHref="#svg-arrow" /> </svg> //styling .user-quickview .svg-arrow { fill: #fff; position: ...

Array automatically updates its values

.... import * as XLSX from 'xlsx'; ... I am currently parsing a .xlsx file in an Ionic 4 application. showData() { let fileReader = new FileReader(); fileReader.onloadend = (e) => { this.arrayBuffer = fileReader.result; let data ...