Why does isDisplayed method in Protractor return "No element found using locator" instead of a boolean value?

In my code, I've created a function called isElementDisplayed which features a call to element.isDisplayed.

I'm curious as to why the isDisplayed method sometimes returns No element found instead of a boolean value.

isElementDisplayed(element: ElementFinder) {
    return element.isDisplayed();
}

Answer №1

To determine if an element is visible, use the isDisplayed() method. However, to check if an element exists in the DOM, you should utilize isElementPresent() or isPresent():

expect(browser.isElementPresent(element(by.id('ELEMENT_ID_HERE')))).toBe(false);
expect(element(by.id('ELEMENT_ID_HERE')).isPresent()).toBe(false);

For additional insights:

  • Utilize element by css to verify element existence in Protractor

Answer №2

An error occurred while attempting to locate the element. Utilize a try and catch block to handle and return false.

try{
return element.isDisplayed();
} 
catch (Exception e) 
{
return false; 
// e.getMessage(); // print out the exception message if needed
}

Answer №3

If you're looking to ensure visibility of an element globally, consider implementing a method and utilizing it throughout your code. Here's an example:

public static boolean ElementVisible(By element, WebDriver driver) {

        // Set maximum attempts and sleep time
        int maxAttempts = 2;
        long sleepTimeInMillisForEachIteration = 500;

        for (int counter = 0; counter <= maxAttempts; counter++) {
            try {

                    driver.findElement(element);        

                return true;
            } catch (NoSuchElementException | ElementNotVisibleException e) {
                if (counter == maxAttempts) {
                    return false;
                }
                try {
                    Thread.sleep(sleepTimeInMillisForEachIteration);
                    continue;
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
            }
        }
        return false;
    }

This method will interact with the element if it is visible, handling exceptions and returning false otherwise.

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

how to adjust the width of a window in React components

When attempting to adjust a number based on the window width in React, I encountered an issue where the width is only being set according to the first IF statement. Could there be something wrong with my code? Take a look below: const hasWindow = typeof ...

Has the recent update to the latest Google Chrome version (Version 87.0.4280.66 (Official Build) (64-bit)) included a change where the "chromedriver.exe" process is now named "Google Chrome"?

In previous versions of the chromedriver software, I used to observe a process labeled as chromedriver.exe in my task manager. However, in the newer version (87), it appears that this process has been renamed to Google Chrome. As a result, I would typical ...

When attempting to retrieve and process a JSON from the internet, I encounter "undefined" errors despite the fact that the data appears correctly in the log

I'm having trouble processing the JSON data received from a server. When I attempt to use .forEach on it, I receive an error stating that the data is undefined even though the console.log shows the correct values. What could be causing this issue? Is ...

Declaring scoped runtime interfaces with Typescript

I need to create a global interface that can be accessed at runtime under a specific name. /** Here is my code that will be injected */ // import Vue from "vue"; <- having two vue instances may cause issues // ts-ignore <- Vue is only ava ...

Extracting Job Titles from LinkedIn Profiles

Currently, my code is designed to search for job titles on LinkedIn (e.g. Cyber Analyst) and gather all the links related to these job postings/pages. The goal of the code is to compile these links into a list and then iterate through them to print out th ...

Styles are not applied by Tailwind to components in the pages folder

NextJS project was already created with tailwind support, so I didn't have to set it up myself. However, when I add className to an HTML element in a component within the pages/ folder, it simply doesn't work, even though the Elements panel in D ...

Can Selenium be used for testing driven by Excel spreadsheets?

With Sahi, I was able to input the required functions into a spreadsheet and have them executed. It allowed for various combinations which led to different outcomes. Is it possible to achieve something similar using selenium? I am interested in selecting a ...

Utilizing Selenium WebDriver to Locate Elements Using Relative XPath Based on Their Text Content

I am currently utilizing Selenium webdriver in conjunction with Java. My main challenge lies in identifying elements within dynamic dropdown lists, as accessing them by exact id/name/xpath is proving to be difficult. I have resorted to locating these elem ...

Is there a method to bypass the Instagram bot detection system?

Despite trying various methods, I have been unsuccessful in creating automated Instagram accounts using a program developed with Python and Selenium. Even after implementing all security measures, Instagram still detects and blocks my attempts to create ne ...

Utilizing Python to interact with the TOR browser using the Selenium library

After conducting thorough research, I came across this solution: from selenium import webdriver profile = webdriver.FirefoxProfile() profile.set_preference('network.proxy.type', 1) profile.set_preference('network.proxy.socks', '12 ...

"Creating a Typescript property that is calculated based on other existing properties

I am working on a Typescript project where I have a basic class that includes an `id` and `name` property. I would like to add a third property called `displayText` which combines the values of these two properties. In C#, I know how to achieve this using ...

Encounters SessionNotCreatedException error when executing test in Firefox

I am currently utilizing the following versions: Selenium: 3.6.0 Mozilla: 56.0 Gecko Driver: V 0.19.0 Whenever I execute the testng.xml file for Mozilla Firefox, it throws the subsequent exception: Log: org.openqa.selenium.SessionNotCreatedException ...

Having trouble with Selenium's DeselectAll function on an HTML SELECT element with the multiple attribute?

I found a helpful HTML code that I am currently using: <select name="cars" multiple> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="opel">Opel</option> <option va ...

Testing simultaneously two pages with Selenium

Currently, I am working with two web pages A and B. My goal is to ensure that any changes made on page A are correctly reflected on page B. To achieve this, I plan to run two simultaneous Selenium tests - one for page B and another for page A. The test for ...

Tips for including multiple directives in a component

Apologies in advance for my lack of clarity in expressing this question, which is why I am seeking assistance rather than finding the solution on my own. My query pertains to loading a component within another one and specifying it in the directive. Below ...

Is there a way to upload inventory data into Registroid P.O.S. system using Ruby, Selenium, and Test-Unit?

When faced with the challenge of importing inventory into Registroid, it became clear that there was no easy solution. A friend of mine needed to quickly import a large amount of product data for her pop-up boutique, so I decided to take matters into my ...

Tips on delaying the return of the Angular compiler until the subscription is complete

I'm facing an issue with a function that needs to return a value while containing a subscription. The problem I'm encountering is that the return line is being executed before the subscription ends, testFunc(){ let objectType; let modul ...

typescript decorator implemented on a class that is nested within another class

Is it possible to decorate a nested property within a class? Let's explore with an example: function log(name: string = 'DecoratedProp') { return function logHandler(target: any, field: any) { // get the key ...

A Guide to Retrieving Parameters and Request Body using Express and Typescript

When I use the PUT method, I encounter this issue: const createFaceList = (req: Request<{faceListId : string}>, res: Response, next: NextFunction) => { console.log(req.body.name); console.log("faceListID = " + req.params.faceListId); a ...

Changing a complex object within a nested array of a BehaviorSubject

I'm currently working on an Angular app. Within my service, DocumentService, I have a BehaviorSubject that holds an array of Documents. documents: BehaviorSubject<Document[]> Let me provide you with some insight into the various classes I' ...