Retrieve an AngularJS variable using Java Selenium's JavascriptExecutor

Within this div, an AngularJS ng-click attribute is utilized to assign a value to a variable upon clicking the div.

<div id="id"
     ng-click="foo.bar = true;">
     Set bar variable on foo object to true
</div>

The following Java code snippet demonstrates the use of Selenium to click on the mentioned div element.

By upload = By.id("id");
driver.findElement(uploadCensus).click();

Encountering a situation where running the Java code causes AngularJS to hang indefinitely. The issue stems from the inability to set the foo.bar variable when the div is clicked. Implementing a workaround that directly sets the variable with the following code:

By upload = By.id("id");
((JavascriptExecutor) driver)
    .executeScript("foo.bar = true;",   
    driver.findElement(upload));

A stack trace error message reports that 'foo' is not defined, indicating the need for globally accessing the variable buried inside AngularJS source code. Despite efforts to search for and manipulate the elusive variable within the unminified index, the task proves challenging. Seeking advice on how to locate and modify the 'foo.bar' variable through JavascriptExecutor.

If the current approach to triggering the ng-click event seems inefficient, alternative suggestions are welcome. While Protractor could offer a solution, constraints in deploying this AngularJS application within an enterprise setting necessitate sticking with Selenium. Assistance in resolving this dilemma would be greatly appreciated...

Answer №1

When answering questions, always provide direct answers (avoid using it for personal cases)

In Angular, variables are isolated within their scope. To set a variable, you need to access the scope and then assign the value to it.

angular.element("#id").scope().foo.bar = true;

It's important not to use this method for your specific case as testing an application at the system level requires running tests in a way that mimics user actions.

Suggested Approach: Utilize Angular testability in Java

Whatever functionality Protractor offers, your Java tests can achieve as well. Both tools utilize Selenium bindings underneath, executing code in the same browser environment.

The waitForAngularMethod is imperative and should be included in your tests. You can execute similar JavaScript code using JavaScriptExecutor during explicit waits.

If you prefer JavaScript, refer to the waitForangular method implementation in Protractor. It involves simple validation checks with callbacks for waiting purposes.

Your Java code snippet for creating the expected condition while waiting for Angular

String waitForAngularJs ="Your javascript goes here"; // If lengthy, consider reading from a file and storing here.
ExpectedCondition<Boolean> waitForAngular= new ExpectedCondition<Boolean>() {
            public Boolean apply(WebDriver driver) {
                return ((JavascriptExecutor) driver).executeAsyncScript(waitForAngularJs).equals(true);
            }
};

 WebDriverWait wait = new WebDriverWait(driver, 60);
 wait.until(waitForAngular);

Modify the Angular JavaScript Wait Function for Java execution (not validated yet):

This function requires two parameters - a root locator hook and a callback. I have defined a callback function to simply return true and set the hook with the root locator which is [ng-app].

// Code block provided

Importance of Waiting for Angular and its Logic

Waiting for Angular is essential due to its usage of HTML templating, two-way data binding, AJAX requests, and routing. After page navigation, waiting for these operations (including requests & promises) to complete ensures proper responsiveness of HTML elements.

Assessing Angular Testability

To verify Angular testability, Angular provides a method for checking individual components or all testabilities present on the page.

Ensuring Completion of HTTP Requests

Prior to checking Angular testability, ensure there are no pending HTTP requests by querying the number of pending requests with:

angular.element(document).injector().get('$http').pendingRequest.length

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 on altering the color of a circle's radius within Google Maps

I'm trying to add a circular radius on a Google Map. Even after reviewing the Google Maps API documentation, I'm still unsure of how to accomplish this task. Below is the code snippet I have been working with: const MyMapComponent = compose( ...

When trying to iterate over a CSV file using Selenium and Pandas in Python, I encountered the error message: "TypeError 'io.BufferedWriter' object is not subscriptable."

Hi there! I'm currently exploring how to integrate data from a csv file into my selenium script. Here's what I have so far: f = pd.read_csv("Data.csv") f.head() for index in range(len(f.index)): Bestellnummer = f["Bestellnumme ...

Discover the exact location of an HTML element within an iframe

I am currently attempting to determine the position of an element that is within an iframe. I have written the following code for this purpose: // Custom function to calculate the position of an element on the page function getElementPosition(elem){ var ...

Guide to creating scrolling parallax web page effects with JavaScript

I am new to Javascript and recently came across a website with a fascinating scroll parallax effect. The images on the site overlap and move as you scroll, similar to the effect on this particular website Example website: let scrollH; let photo1 = do ...

A guide on using Selenium in Python 3.8 to patiently wait for a text field to become editable

I decided to take on a fun project of creating a selenium bot that can play Typeracer for me. However, I am encountering some difficulty in getting the bot to wait for the countdown to finish before it starts typing. One workaround I found is to wait for t ...

Having trouble accessing the ng-model within ng-repeat in the controller of an AngularJS component

One approach I am considering is to use ng-model="model.ind[$index]" in order to keep track of the active tag. This way, when I click on a tag (specifically the 'a' tag), both the parentIndex and $index will be passed to my controller. Subsequent ...

What are the limitations of using a JS file within an Angular application?

I am struggling to integrate some js methods from a file into an angular application. Unfortunately, the browser is unable to recognize the js file. I have tried following the guidelines in this SO post, but the browser still cannot locate the file in the ...

Retrieving text that has been HTML-escaped from a textarea using jQuery

Within my HTML file, I have a <textarea id="mytextarea"></textarea>. Suppose a user inputs the following text: <hello>, world! How can I retrieve res = "&lt;hello&gt;, world!"; based on the user's input? The current code s ...

Resolving Angular ui-router, handling successful HTTP requests, and using state parameters are important

My objective is to: Firstly, insert a new record into the database using an HTTP POST request, resolve it with stateProvider, retrieve the new ID, and change the view and stateParams accordingly. This is the code for my HTTP POST service: myApp.service( ...

Whenever I relocate the button's position within the Bootstrap framework, it seems to end up in a completely different

body <div class="container" style="margin-top: 70px;"> <div class="formlogin bg-light bg-gradient shadow-lg p-3 mb-5 bg-body rounded col-8"> <p id="signText"> Signin Fo ...

Is there a way to retrieve time data from a different server through AJAX?

I am in need of obtaining time information from an online source, whether it be an NTP server, JSON time server, or simply an HTTP Header. The precision is not important to me, but the requirement is that I must get the time from an online source. Unfortun ...

Are elements loaded and hidden by ng-hide and ng-show, or does loading only occur with ng-show?

Is this method of programming effective for handling large elements such as 10 mb images? Are there alternative solutions that would work better? ...

Working with a Mix of Properties in Styled Components

Incorporating a button component with material design using styled-components is my current task. This component will possess various props including size, icon, floating, etc. However, managing the numerous combinations of props has become quite overwhel ...

Issue encountered during compilation of cordova application

While using cordova CLI version 6.2.3 to build my app, I encountered an error in the console during the build process: ANDROID_HOME=/usr/lib/android-sdk JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64 /usr/lib/jvm/java-8-openjdk-amd64/bin/java: symbol lookup ...

What is the best way to save the current state data in AngularJS?

Encountering an issue here. To view the problem, check out this Plunker link -> In my Angular JS project, I need to save the current state data somewhere other than local storage. On one page, I have a list of models (cards), each containing two tabs. ...

Is it possible to include HTML in a response when verifying emails with Node JS and Angular?

Before diving in, I want to make it clear that I have experience using APIs created in NodeJS with Angular. However, I am encountering a bit of a challenge. The issue at hand involves a function that verifies the email used during registration: exports.co ...

Ruby: The Chrome browser refuses to open

After installing the gem 'webdrivers', '~> 4.0', I attempted to launch a chrome browser, but encountered issues. Here is the code snippet: @app = Driver.new(Capybara::Session.new(:selenium_chrome)) Webdrivers::Chromedriver.current_ ...

encountering issues while Deserializing a collection containing children objects of various types

I am facing an issue with deserializing a JSON packet that consists of a header (under PACKET_HEADER) and several different types of messages (under DATA). These messages have a parent class in common: //parent message class public class Message { pu ...

Is there a way to incorporate an image as a texture onto a ply model using three.js?

Can someone help me figure out how to properly load a texture for a 3D model in a ply format? I'm working on an HTML file where I'm using three.js along with plyloader.js to load the model. However, I'm having trouble loading the texture co ...

Generating basic mesh shapes using three.js programmatically

Is there a way to easily generate basic shapes such as ramps, cones, and revolution shapes using only their vertices in three.js? ...