Using Selenium WebDriver to handle Angular requests in Java

I am currently developing tests for an angular-based application and I find myself in need of assistance. The specific task at hand involves creating a mechanism that will wait until all pending requests within the application have been processed before proceeding. In essence, I am trying to interact with a checkbox element that only becomes available once all GET requests have been completed. While using Thread.sleep(2000) temporarily solves the issue, I am aware that this is not a reliable long-term solution.

So far, I have attempted two different approaches:

   AdditionalConditions wait = new AdditionalConditions();
        wait.untilAngularFinishHttpCalls();

 public void untilAngularFinishHttpCalls() {
        final String javaScriptToLoadAngular =
                "var injector = window.angular.element('app-root').injector();" +
                        "var $http = injector.get('$http');" +
                        "return ($http.pendingRequests.length === 0)";

        ExpectedCondition<Boolean> pendingHttpCallsCondition = new ExpectedCondition<Boolean>() {
            public Boolean apply(WebDriver driver) {
                return ((JavascriptExecutor) driver).executeScript(javaScriptToLoadAngular).equals(true);
            }
        };
        WebDriverWait wait = new WebDriverWait(SharedDriver.getDriver(), 20); // timeout = 20 secs
        wait.until(pendingHttpCallsCondition);
    }

However, I encountered the following error:

org.openqa.selenium.WebDriverException: unknown error: Cannot read property 'element' of undefined (Session info: chrome=59.0.3071.115)
(Driver info: chromedriver=2.31.488763 (092de99f48a300323ecf8c2a4e2e7cab51de5ba8),platform=Windows NT 10.0.15063 x86_64) (WARNING: The server did not provide any stacktrace information) Command duration or timeout: 5 milliseconds Build info: version: '2.31.0', revision: '1bd294d185a80fa4206dfeab80ba773c04ac33c0', time: '2013-02-27 13:51:26' System info: os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_121' Driver info: org.openqa.selenium.chrome.ChromeDriver Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.31.488763 (092de99f48a300323ecf8c2a4e2e7cab51de5ba8), userDataDir=C:\Users\lpaczek\AppData\Local\Temp\scoped_dir13872_15975}, takesHeapSnapshot=true, pageLoadStrategy=normal, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=59.0.3071.115, platform=XP, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true, setWindowRect=true, unexpectedAlertBehaviour=}]

My second attempt involved the following code snippet:

   WebDriverWait wait = new WebDriverWait(SharedDriver.getDriver(), 15, 500);
        wait.until(AdditionalConditions.angularHasFinishedProcessing());


public class AdditionalConditions {
    public static ExpectedCondition<Boolean> angularHasFinishedProcessing() {
        return new ExpectedCondition<Boolean>() {
            @Override
            public Boolean apply(WebDriver driver) {
                return Boolean.valueOf(((JavascriptExecutor)
                        driver).executeScript("return (window.angular !== undefined) && (angular.element(document).injector() !== undefined) && (angular.element(document).injector(). get('$http').pendingRequests.length === 0)").toString());
            }
        };
    }

Unfortunately, this resulted in a timeout after 15 seconds indicating that it was not successful. It appears that my understanding of executing JavaScript code is limited, and I would greatly appreciate any guidance or assistance you can offer in resolving this issue.

Answer №1

Instead of rushing, you should allow Angular to complete its tasks before proceeding.

If you use the ngwebDriver package, you can achieve this functionality easily.

var driver = new NgWebDriver(driver);

driver.waitForAngularRequestsToFinish();

Answer №2

For a potential solution, you may want to consider the suggestion provided at

Alternatively, you can explore further details on https://github.com/swtestacademy/JSWaiter (check out JSWaiter.java), although it could be slightly outdated compared to the referenced article.

public class JSWaiter {
    // Class implementation details for waiting in Selenium with JavaScript and Angular
}

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

Tips for establishing a connection with the MovieDB API web service

As a beginner in the world of web services, I am currently in the learning phase. Unfortunately, there is not much online content available that provides information on how to use the MovieDB API web service. For now, my main focus is on trying to display ...

"Enhance your website with powerful AJAX functionality using the October CMS

Can you help me troubleshoot this AJAX error I'm encountering when trying to call an AJAX action? The error message is indicating an 'Invalid handler name.' The correct format for the handler name should be "onEvent" I am attempting to u ...

Unable to reach the object property while using the $.each method

Upon receiving an object from an ajax request, I am using $.each to iterate through all the appointments in the object. However, I am encountering an issue where the object appears to be undefined within the $.each loop. Here is the code snippet for my req ...

The MongoDB query isn't functioning properly as the Match operation is returning an array with no elements

I am currently facing an issue with creating an aggregation pipeline. Everything seems to be working fine in the code until it reaches the $match section, which returns nothing. Here is the snippet of my code: var userId = req.params.UserId const m ...

The Heroku deployment was a success, however, MongoDB failed to save any data

For the development of our app, we chose to use Heroku as our hosting platform and utilized Java and Dagger for building it. Despite successfully deploying the app on Heroku, we noticed that no data from the Java code for testing was being stored in MongoD ...

Configuring environment variables for a Spring Boot application running on Ubuntu version 22.04

I am trying to configure the following values in my environment (Ubuntu 22.04) spring.datasource.url = jdbc:mysql://localhost:3306/abc?useSSL=false spring.datasource.username = root spring.datasource.password = root I have set these values in the environm ...

Obtaining the value of an item in an unordered list

Hi everyone, I have been trying to extract the value of <li> elements that display images horizontally. Below is the HTML code I am working with: <div id="layoutInnerOptions"> <ul id="navigationItemsContainer" class="layouts_list"> <l ...

Tips for inserting an HTML table into a div element using JQuery/JavaScript

I currently have a navigation bar with only two items. While I may potentially add more items in the future, for now I am content with just these two. Upon opening the page, my goal is to display the content of the first item in the navigation bar. Each it ...

Ways to maintain group settings for a Telerik MVC Grid connected to Ajax

Currently, I am seeking guidance on how to persist grouping settings on an Ajax bound Telerik ASP .NET MVC grid. My goal is to have the grid display revert back to its previous settings when a user navigates away to a detail screen and then returns to the ...

Drop down calendar in Javascript

I am in the process of developing a virtual JavaScript calendar dropdown feature. I aim to have the correct number of days displayed upon selecting a month, but currently, no days appear when I make a selection. Can someone please assist me with this iss ...

Chrome on OSX Mavericks threw a RangeError because the maximum call stack size was exceeded

While attempting to run an Angular app using linemanjs in Chrome on a Mac, I encountered the following error: Uncaught RangeError: Maximum call stack size exceeded An interesting observation is that the site functions properly on Chrome on a Windows mach ...

JavaScript Tip: Effortless method to confirm the presence of duplicate values within an array

Similar Question: Best method for identifying duplicate values in a JavaScript array If I have an extensive array containing thousands of elements, I am looking to check if there are 2 or more elements with identical values and return true. I unders ...

Is there a way to dismiss a modal window from the parent?

How can I close a modal window from its parent? This task seems quite challenging to accomplish. Essentially, I am opening a non-modal window. In some cases, the user may open a modal window from this non-modal window. If I close the non-modal window, I al ...

Why does my anchor disappear after a second when clicked to show the image?

Hi everyone, I'm having an issue with a dropdown menu that I created using ul and anchor tags. When I click on one of the options, an image is supposed to appear. However, the problem is that the image shows up for just a second and then disappears. I ...

What is the best way to integrate options within my object-oriented Python script?

Can anyone assist me with implementing options in my OOP code? I don't want the browser pop-up to appear every time I run the code, so I need to include the headless option. However, I'm struggling with how to do this. I have experience making m ...

A step-by-step guide on implementing lazy loading for a specific div section using either AJAX or Java

I'm facing an issue with a div section that contains numerous tables pulled from my database. The main problem here is that when the page loads, it takes a considerable amount of time to fully load all the content, causing a significant delay. Could ...

Having trouble with Axios PUT request not sending complete data to the server using JavaScript

One issue I'm encountering is that when sending an axios request with specific data, not all of the data gets updated in the user model. Here's a look at my code: Here is the Front-End code with axios request: import axios from "axios" ...

React / Next.js Rendering Problem, Data Discrepancy Between Client and Server

A new feature has been added to a webpage where an image background and a city name are displayed on top of it. The data file that generates these image backgrounds and city data consists of a standard array of objects. The challenge lies in dynamically l ...

Retrieve the most recent ajax request and cancel any other ones

I've been exploring this issue and it seems fairly straightforward, but I'm having trouble finding a solution. I have several requests that call different URLs. However, for each URL, I only want to receive the last result from the same URL being ...

What is the process for submitting and storing a collection of files in a database as a list?

I am trying to implement a feature in my MVC project where users can upload multiple files and see them listed before submitting the form. However, I am facing some challenges with finding a solution for this. Demo: My goal is to allow users to add multi ...