Retrieve the information from the AJAX request executed within Selenium

I am currently developing a test to verify that a link on a page is correctly referencing the intended destination (link generated dynamically). In order to test this link, I plan to use an AJAX call in Selenium to retrieve the correct URL from the server and compare it. However, I am facing difficulty in retrieving the value from the AJAX call made in Selenium.

JavascriptExecutor jse = (JavascriptExecutor)driver;
String jsCode = 
            "var str = $.get('/User/GetDynamicURL/', function (result) {"
                        + "console.log('result: ' + result); "
                        + "return result;"
                    + "})"
           + "return str;";
String dynamicURL = (String) jse.executeScript(jsCode);

Despite seeing the expected output in the console, my code is not functioning properly. I am encountering the following exception:

java.lang.ClassCastException: com.google.common.collect.Maps$TransformedEntriesMap cannot be cast to java.lang.String

When running the code:

var str = $.get('/User/GetDynamicURL/', function (result) {
    console.log('result: ' + result);
    return result;
});
str;

If I inspect str in the console of my browser, I receive an object resembling:

{readyState: 1, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}

Additionally, accessing str.responseJSON returns the desired URL.

I would appreciate any guidance on resolving this issue with my code. Thank you!

Answer №1

In order to compare the expected URL with the actual URL of a link, you can extract the href value of the webelement and store it in a variable. Then, simply use an assertion to check if the two URLs match:

String expectedURL = "https://whatever...";
String linkURL = driver.findElement(locator).getAttribute("href");
Assert.assertEquals(expectedURL , linkURL);

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

Steps to extract information from a WebElement

While in debugging mode, I noticed that the locator for a particular element on the page is shown as: By.name: NameOfMyElement_123. Now, my query is how can I extract and parse the string (By.name: NameOfMyElement_123) using Java to identify the type of t ...

Numerous applications of a singular shop within a single webpage

I have a store that uses a fetch function to retrieve graph data from my server using the asyncAction method provided by mobx-utils. The code for the store looks like this: class GraphStore { @observable public loading: boolean; @observable ...

Using Thymeleaf in a Spring Boot application, the modal automatically closes after submission

How can I keep the modal open when I click the submit button? I want to reload an existing modal form when I click submit. The code form is in fragment/header, and when I click the "login" button, the modal shows up. The issue is that in views/loginForm, ...

Enhancing Website Visibility: Utilizing PHP and JQuery to Update Page Content for Viewers

Imagine having a social networking platform where users can post updates and see them appear in real-time on their timeline. The challenge arises when these updates are only visible to the user currently logged in on a specific device. How can we utilize j ...

Obtaining a Row from a Grid with Selenium

Having recently started using Selenium/Katalon, I've encountered a problem with my script. Specifically, I'm receiving an "unable to locate element" error for the table element that I have specified. I suspect that I might be referencing the wro ...

The function 'send' cannot be called as it is undefined (response is undefined) within Express.js

I have encountered a challenge while trying to pass a variable from my index.html to the database (maildata.js) through app.js (server) and retrieve the corresponding data. I have successfully retrieved the data from the database, but I am facing difficult ...

To restrict users to specific values and require them to include a $ sign in their input for my program, follow these steps

//Payment Process System.out.println("Order payment"); System.out.println("-------------"); System.out.println(""); System.out.printf("$%.2f needs to be paid. Please enter coins or notes: " ...

Using JSON with Google Chart Tools

When referring to this example at , it is noted that the method data.addRows() requires a list of lists. A URI (/data/mydata.json) can be accessed to retrieve the following data: [["Canada", 66], ["Turkey", 10], ["Hungary", 23], ["Italy", 49]] Despite a ...

Manage the application of CSS media queries using JavaScript

Is there a method to control which CSS media query a browser follows using JavaScript? As an example, let's say we have the following CSS: p { color: red; } @media (max-width: 320px) { p { color: blue; } } @media (max-width: 480px) { p { col ...

The ajax call I made is not retrieving any data, only returning an empty array

I am having trouble passing data from JavaScript to PHP through AJAX. Even though I have passed some data, the output is showing as an empty array. Can someone please assist with this issue? <html> <head> <title></title> ...

How to smoothly transition a div from one location to another using animations in an Ionic3-Angular4 application

I'm attempting to incorporate some animation into my Ionic 3 mobile app. Specifically, I want to shift a div from one location to another. In the code snippet provided below, I am looking to move the div with the "upper" class after the timeline-item ...

Is it possible to enlarge pixel art in EaselJS without causing blurriness?

As I develop a game using EaselJS with pixel art that I'm enlarging, I've encountered an issue. Whenever I scale the art, the image becomes blurry. Is there a method to have it drawn using nearest neighbor filtering? ...

Creating a script to identify and separate odd and even numbers between 1 and 1000 using Javascript

I have been working through a book on Javascript that includes solved examples, but I've come across one example without a solution. I am interested in learning how to complete it. The task at hand is to write a script in Javascript (for a browser) t ...

Struggling to integrate Ajax with Angular framework

Looking to learn Angular. Attempting to integrate Angular with AJAX calls. Whenever I try to access http://localhost:9091/jerseyservlet/jerseyrest/org/orgId/DEY using a browser or any REST client, the following response is displayed: <users> & ...

Guide on simulating an incoming http request (response) using cypress

Is there a way to mock a response for an HTTP request in Cypress? Let me demonstrate my current code: Cypress.Commands.add("FakeLoginWithMsal", (userId) => { cy.intercept('**/oauth2/v2.0/token', (req) => { ...

Exploring the intricacies of d3 force layout in the Firefox

Currently, I am utilizing D3.js to create a force layout for animated circles moving around. While it performs exceptionally well in webkit browsers, I am experiencing significant slowness and clunkiness in Firefox. Someone else encountered a similar issu ...

A quicker alternative to Java2D Area calculations

I have been utilizing Java2D along with apache batik to render some rather large svg images. Although things are running smoothly so far, I am facing performance issues when it comes to areas. There are three main tasks that I need to accomplish: Combin ...

What are some ways to integrate the features of ctype.h into JavaScript?

How can glibc's ctype.h be effectively translated into JavaScript? While I believe it is possible, I am struggling to locate the tables and bitshifting operations used in the C source code. What are the best techniques to employ in this situation? isa ...

How to make views in React Native adjust their size dynamically in a scrollview with paging functionality

Has anyone successfully implemented a ScrollView in React Native with paging enabled to swipe through a series of images? I am having trouble making the image views fill each page of the scroll view without hardcoding width and height values for the image ...

Prevent excessive clicking on a div element

I am facing a simple issue that I haven't been able to resolve yet. I want to prevent multiple clicks on a button before an AJAX call is complete. This is what I have tried so far: <button id="btn_pay"></button> $("#btn_pay").click( fun ...