What is the best way to communicate between the Browser and WebDriver using Protractor?

As I work on integrating Protractor for running tests on my Angular web application, I leverage a custom Angular service called ApiClient for making API calls. To mock this service, I utilize browser.addMockModule along with angular.module().factory(). This approach allows me to effectively mock all my backend APIs. Below is a snippet of the code I use:

setup() {
  // Implemented in WebDriver.

  // The 'apiRequestsMap' is passed as 'map' to the anonymous function within the module.
  browser.addMockModule(
      'mockDataModule',
      (map) =>
          angular.module('mockDataModule', []).value('apiRequestsMap', map),
      this.apiRequestsMap_);

  const apiModuleMaker = () => {
    const mockModule = angular.module('mockapiModule', ['mockDataModule']);
    mockModule.factory(
        'apiClient',
        ($q, apiRequestsMap) => ({
          request: (req) => {
            // Within the Browser.
            // Utilizing 'apiRequestsMap' for mocking API calls.
          }
        }));
  };
  browser.addMockModule('mockapiModule', apiModuleMaker);
  browser.get('www.mywebpage.com/example');
}

This method works effectively for setting up mock APIs in my Protractor tests. The key aspect is the ability to pass the this.apiRequestsMap_ variable from WebDriver to the Browser as apiRequestsMap.

Now I am curious - can I reverse this process? How can I send a variable from the Browser back to WebDriver?

My initial attempt involved modifying the apiRequestsMap object that was passed in. However, it seems like this was a one-way transfer. For instance, when I set apiRequestsMap.aVar = 5; in the Browser, it does not affect this.apiRequestsMap_.aVar.

In exploring the Protractor API, I came across browser.getRegisteredMockModules. Unfortunately,

console.log(JSON.stringify(browser.getRegisteredMockModules()));
yielded [null, null, null, null, null].

I apologize for the extensive code and details provided. I am navigating through uncharted territory, so I erred on the side of caution in omitting parts of the code that might impact its functionality. Is there a better approach to directly mock API calls within WebDriver? That could serve as a viable workaround.

Alternatively, I may consider submitting a feature request/bug report to the Protractor developers.

Answer №1

If you want to run Javascript code directly in the Browser using Protractor, you can easily do so.

Simply add the following code snippet to your Javascript:

window.__mydata__ = {count: 5, label: "xyz"};

You can then access this data by executing JavaScript code with Selenium. In Protractor, you can achieve this with the following:

browser.executeScript('return window.__mydata__;');

The returned object from window.__mydata__ should be convertible to JSON format. This data will persist in your test code until the page is refreshed. For a more in-depth explanation, you can refer to

Access window object / browser scope from protractor

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

The reactivity of a Vue.js computed property diminishes when it is transmitted through an event handler

Within my main application, I've implemented a Modal component that receives content via an event whenever a modal needs to be displayed. The Modal content consists of a list with an associated action for each item, such as "select" or "remove": Vue. ...

Issue with Vue Router unable to locate query parameters

Using Vue 3 along with Vue Router 4 and a web hash history router I encountered an issue where a URL with a query parameter was not being recognized by Vue, leading to unexpected redirect problems in my application. For instance: Original URL: Https://e ...

ReactJS component update issueUpdate function malfunctioning in ReactJs

Hey there, I could really use some assistance with a React component that I'm working on. I'm fairly new to React and what I'm trying to do is retrieve a list of available languages from the backend and display them in a dropdown. Once the u ...

Are you unsure whether to use Ajax or jQuery? If you need assistance in adding parameters to

Currently delving into ajax/jQuery and encountering some hiccups. Here's the code snippet: .click(function() { var period = 'ALL'; if ($('#registerat input:checked').val() != 'ALL') period = ...

What could be causing my Vue code to behave differently than anticipated?

There are a pair of components within the div. When both components are rendered together, clicking the button switches properly. However, when only one component is rendered, the switch behaves abnormally. Below is the code snippet: Base.vue <templa ...

Customize AngularJS: Make the default child view for UI-View stand out

I came across a guide on how to set up nested states in AngularJS using UI Router, and followed it to create a page with two child views. Now that everything is set up, clicking on specific links displays the subviews as expected. Below is my app.js file ...

How can you replicate a mouseover event using Selenium or JavaScript?

I have recently been working on a task involving web UI automation using Selenium, Javascript and SeLion. My goal is to capture a screenshot of a scenario similar to the Google homepage, specifically focusing on the "Search by voice" feature when hovering ...

Is a component updating an unregulated text input to be controlled?

Whenever I attempt to input information into the form and save it in the state, I encounter the following issue: Warning: A component is converting an uncontrolled text input to a controlled one. Input elements should not transition between being contro ...

Efficient Ways to pass information to an Object within a nested function

const http = require('https'); exports.ip = async (req, res) => { const ip = req.body.ip; const ip_list = ip.trim().split(' '); const count = ip_list.length; var execution_count = 0; var success = {}; // **Creati ...

Ways to dynamically refresh a Vue component when data is updated without the need to manually reload the

After fetching data using axios, I noticed that my Vue component doesn't update automatically after a click event or when the data changes. As a workaround, I have to refresh the page to see the updated data. Is there a simple solution to this issue? ...

Is there a way to create Angular components sourced from an external library using JavaScript?

I'm currently developing an Angular project and leveraging an external component library called NGPrime. This library provides me with a variety of pre-built components, including <p-button> (which I am using in place of a standard <button> ...

How can I utilize customToJSON in Sails 1.0 within an Action2 function?

Currently, I am facing an issue with my user model that requires the implementation of a customToJSON method to remove the password field from the returned JSON object. Everything works fine when I include "responseType" in the "exits" with a value of "jso ...

Encountered an Error: Trying to use a function that is undefined - While utilizing Jquery Tabs

Working on implementing Jquery Tabs using the "description" and "reviews" li tags as tabs. Testing it out here . Everything seems to be functioning correctly here Key Points: This is Wordpress Multi-Site setup. The issue occurs in certain folders or "si ...

Explore an array of elements to find the correct objectId stored in mongodb

element, I am faced with a challenge of searching through an array of objects to find a key that contains nested object id for populating purposes. Exploring My Object { service: 'user', isModerator: true, isAdmin: true, carts: [ ...

Using ng-init to pass a JSON object

I'm attempting to pass a JSON Object to my application using ng-init and the stringify method, but I am encountering an error. Instead of working as expected, I am getting a Lexer error. Lexer Error: Unexpected next character at columns 8-8 [#] in ex ...

Having trouble setting up discord.js on my device, getting an error message that says "Unable to install discord.js /

Trying to install Discord.JS by using the command npm install discord.js seems to be successful at first, but unfortunately it doesn't work as expected. Upon running the index.js file, an error message pops up indicating that the module discord.js is ...

Transform the data format received from the AJAX request - modify the input value

I have a data variable that contains an object structured as follows: { "details": { "id": 10, "name": John Doe, "hobbies": [{ "id": 1, "name": "Football" }, { "id": 2, "name": "Badminton" }, ...

Error encountered: JSON parsing failure at position 351 due to an unexpected token "}". This issue was found within the JSON object containing the property "license" with the value of "

I'm a newcomer to JavaScript and JSON, and I'm currently in the process of uploading my NPM package. However, I keep encountering an error when I attempt to publish it: Unexpected token } in JSON at position 351 while parsing near '..."lice ...

Display an iframe using React in multiple areas across the app with the same state

Within my React scenario, we display a BI dashboard using an iframe on the page, allowing users to interact with the frame and potentially filter the BI data. I've developed a feature that enables this iframe to expand into a full-screen dialog for en ...

Navigating in next.js

Whenever I run my program, it displays the following error message: Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component ...