Record Selenium requests made to REST APIs

When conducting integration tests using Selenium as the test runner and the webdriver.io JavaScript library for the Selenium API, my testing scenario involves loading an HTML page and clicking on a button. I am specifically aiming to verify whether a GET REST call was made.

While exploring options, I came across a webdriver.io plugin called webdriverajax that purportedly aligns with my needs. Unfortunately, it does not seem to work as expected.

Does anyone have suggestions on how to effectively capture REST calls in this testing environment?

Answer №1

To achieve this functionality, you can create a separate custom HttpClient class outside of your Selenium code. Selenium itself does not have built-in support for this type of feature.

For example, you can set up a scenario where clicking a button triggers a call to a REST service. You can extract the URL from an element in the HTML DOM and then use custom code to verify if the URL is reachable or not. Depending on the status code received or another criteria you define, you can determine whether the test has passed or failed.

Sample Code: FileDownloader.java

private String downloader(WebElement element, String attribute) throws IOException, NullPointerException, URISyntaxException {
        // implementation details here
    }

TestClass.java

@Test
public void downloadAFile() throws Exception {
       // testing logic here
    }

Here is a reference link for further information.

Note: While this may not perfectly align with your requirements, it can serve as a starting point that you can adapt to suit your specific needs.

You can also explore using BrowserMob Proxy to achieve similar functionalities.

Answer №2

The issue arose from the incompatible webdriver.io version. It seems that webdriverajax functions properly only with v3.x of webdriver.io and not with v4.x, which is what I was using - v4.5.2.

Instead of relying on a plugin, I opted to create a mock for the window.XMLHttpRequest open and send methods. Here's how I did it:

proxyXHR() {
  this.browser.execute(() => {
    const namespace = '__scriptTests';
    window[namespace] = { open: [], send: [] };
    const originalOpen = window.XMLHttpRequest.prototype.open;
    window.XMLHttpRequest.prototype.open = function (...args) {
      window[namespace].open.push({
        method: args[0],
        url: args[1],
        async: args[2],
        user: args[3],
        password: args[4]
      });
      originalOpen.apply(this, [].slice.call(args));
    };
    window.XMLHttpRequest.prototype.send = function (...args) {
      window[namespace].send.push(JSON.parse(args[0]));
    };
  });
}

getXHRsInfo() {
  const result = this.browser.execute(() => {
    const namespace = '__scriptTests';
    return window[namespace];
  });
  return result.value;
}

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

drawing tool with JavaScript and HTML5

Can you help me figure out why my sketchpad isn't working in Processing.js? I've checked my code and there are no errors, but the canvas is not showing up. Any suggestions? Take a look at the code below: function createSketchPad(processing) { ...

How can I find out the identification of the control that is already linked to the element?

Currently, I am in the process of developing a web application using asp.net and c#. As part of this project, I am utilizing sql server reporting services (ssrs) to generate reports, which are then presented on the website. The method of presenting these r ...

There is no output from the Selenium JavascriptExecutor command

I have initialized a JavascriptExecutor but I am not getting the desired result. The object is always null. SeleniumDriver driver = new SeleniumDriver(DriverType.ChromeDriver); driver.get("https://www.xxxxxx.info/"); driver.waitForPageToB ...

Exploring touch events and input focusing on mobile devices using JavaScript

Recently, I integrated a JS touch mapping function into one of my pages sourced from Stack Overflow. This was necessary to enable my jQuery draggables to work on iOS Safari, as drag and drop functionality was not functioning without this mapping. Here is ...

What are the top methods for interacting between Server APIs and Client-Side JavaScript?

Presently, I am utilizing setTimeout() to pause a for loop on a vast list in order to apply some styling to the page. For example, For example: How I utilize setTimeOut: I use setTimeout() to add images, text and css progress bars (Why doesn't Prog ...

Display Vue component before fetching data

I am facing an issue where my component renders HTML before fetching data, resulting in no data being displayed until I make an API call within the component using a link rendering function. Can someone guide me on how to render my component after the dat ...

Checking the status of a mongos connection in Node.js: A simple guide

Imagine a scenario where our Node.JS app is connected to the Mongos process, but suddenly Mongos crashes. How can our app be notified of this failure? var db = null; mongo.MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, mydb ...

Using Express and React with Socket.io

I am currently working on setting up a basic WebSocket connection using Socket.io, Express, and ReactJS. Below is the code for the server: const express = require('express'); const socket = require('socket.io'); const path = require(& ...

Crafting a template for mixing up images and quotes without any specific connection - here's how!

I came across some interesting templates that can generate random quotes and others that create random pictures. My goal is to develop a template that generates both a random quote and a random picture, similar to this example, without any relation betwee ...

Turn off specific default features within Sails.js

Currently, I am working on a backend REST API application using Sails.js framework version 0.10. The main focus of this application will be strictly on REST functionality, with authentication utilizing oAuth bearer tokens. All responses will be formatted i ...

What is the best way to connect a series of checkboxes within a form utilizing Angular?

I created a form with checkboxes that allow users to select multiple options. However, when I submit the form, instead of receiving an array of objects representing the checked checkboxes, I'm not getting anything at all. Here is what I see in the co ...

Retrieving Information from API using Vue.js

In the code snippet below, I am displaying data from an API for all flats on a single page. However, I am facing difficulty in showing the floor number for each flat. The JSON body is as follows: { "response": [ { "fl ...

Error: HTML code being displayed instead of form value in Ajax request output

For the past couple of days, I've been struggling with an Ajax issue that I just can't seem to figure out. Despite looking for a solution online, nothing seems to work. Below is the code snippet that's causing me trouble: <!DOCTYPE html& ...

Retrieving data from a collection with the find() method in a custom date format

Schema for Customer Data Customers.js import mongoose from 'mongoose'; const Customers = mongoose.Schema({ CustomerID: { type: String, default: "" }, Name: { type: String, default: "" }, Email: { type: String, default: "" }, Pho ...

Using Vue.js with the slot-in attribute

Looking to create a unique vue.js template that functions as described below: <CustomComponent></CustomComponent> should produce <div class="a"></div> <CustomComponent>b</CustomComponent> should result in <div class ...

What steps should I take to make sure that the types of React props are accurately assigned?

Dealing with large datasets in a component can be challenging, but I have found a solution by creating a Proxy wrapper around arrays for repeated operations such as sorting. I am looking to ensure that when the data prop is passed into my component as an ...

Images of the captured screens are connected with the cucumber reports at a local level, however, they are not linked

@After public void afterScenario() { if (ScenarioManager.getScenario().isFailed()) { ScenarioManager.saveScreenshot(); } public static void saveScreenshot() { byte[] screenshot = DriverProvider.getScaledScreenshot(2); if ( ...

Guide to Appending "Z" to a Date String Using Moment.js in JavaScript and Node.js

I am struggling to format my date to include the "Z" letter at the end. Despite numerous attempts, I have been unsuccessful. The desired format is "YYYY-MM-DDT00:00:00.000Z," but currently it does not include the Z How can I add the Z using moment? It&ap ...

Running a Selenium script in Firefox fails when executed with sudo privileges

I currently have a simple script that looks like the following. from selenium import webdriver from selenium.webdriver.common.keys import Keys # Initiate a new instance of the Firefox driver browser = webdriver.Firefox() browser.get('https://www.goo ...

Guide to highlighting rows in v-data-table with a click in Vuetify (version >= 2.0)

In my email management system, I utilize a v-data-table to organize emails. When a user clicks on a row, a popup displaying the email details appears. Desired Feature: I am looking to have the rows marked as "readed" (either bold or not bold) after th ...