Mastering Protractor: Opening multiple sites and sending keys

My current task involves creating a script with a list of websites and corresponding amounts in a JSON format:

{
    "URL": [{
            "https://testing.com/en/p/-12332423/": "999"
        }, {
            "https://testing.com/en/p/-123456/": "123"
        },
        {
            "https://testing.com/en/p/-456436346/": "422"
        }
    ]
}

The structure is Link: Amount.

Currently, my goal is to open each website and input the specified amount. For example, opening

https://testing.com/en/p/-12332423/
with an amount of 999

Once this is completed, I move on to the next site, such as

https://testing.com/en/p/-123456/
with an amount of 123, and so forth.

Thus far, I have only been able to make one page work using:

{
    "URL": "https://testing.com/en/p/-12332423/"
}

with the following code:

const userData = require('../globalContent.json');


describe('Add To Cart', function () {

    it('Open Product URL', (done) => {
        browser.driver
            .then(() => browser.waitForAngularEnabled(false))
            .then(() => browser.manage().window().maximize())
            .then(() => browser.get(userData.URL))
            .then(() => done());
    });

    //Hardcoded to write 999
    it('Enter 999 Items', function (done) {
        browser.driver
            .then(() => utils.presenceOf(element(by.id('amount'))))
            .then(() => element(by.id('amount')).clear())
            .then(() => utils.sendKeys(element(by.id('amount')), "999"))
            .then(() => done());
    });

After completing the process for a specific site, I want to redirect to another designated site, such as:

it('Finished all sites', (done) => {
    browser.driver
        .then(() => browser.waitForAngularEnabled(false))
        .then(() => browser.manage().window().maximize())
        .then(() => browser.get("https://finished.com"))
        .then(() => done());
});

I am uncertain about the efficiency of using a dictionary-based list for linking websites to amounts. I welcome any suggestions for improvement but ultimately aim to loop through each site and enter the corresponding amount.

Open first link from JSON list dictionary -> Add amount -> Open second link from JSON -> Add amount -> Repeat until all sites are processed -> Redirect to new page https://finished.com

Given the information at hand, how can I achieve this?

Answer №1

To enhance efficiency, consider merging the steps 'Open Product URL' and 'Enter x items' into one comprehensive step. This will allow you to conveniently loop through the contents of your 'URL' array.

describe('Add To Cart', function () {
  const openUrl = function(url) {
    browser.driver
      .then(() => browser.waitForAngularEnabled(false))
      .then(() => browser.manage().window().maximize())
      .then(() => browser.get(url));
  }

  const enterAmount = function(amount) {
    browser.driver
     .then(() => utils.presenceOf(element(by.id('amount'))))
     .then(() => element(by.id('amount')).clear())
     .then(() => utils.sendKeys(element(by.id('amount')), amount))
     .then(() => done());
  }

  it('Open Product URL and enter x items', (done) => {
    for (const data of userData.URL) {
      const url = Object.keys(data)[0]
      const amount = data[url]

      openUrl(url).then(() => {
        enterAmount(amount);   
      }).then(() => done());
    }
  });

 //... complete the site
}

It is recommended to refine your 'URL' object by assigning appropriate keys as shown below:

{
  "pageProperties": [
    {
        url: "https://testing.com/en/p/-12332423/",
        amount: "999"
    }, {
        url: "https://testing.com/en/p/-123456/",
        amount: "123"
    },
    {
        url: "https://testing.com/en/p/-456436346/",
        value: "422"
    }
   ]
}

This way, you can access its properties as follows:

for (const page of userData.pageProperties) { 
  openUrl(page.url).then(() => {
    enterAmount(page.value);   
  }).then(() => done());
}

// and remember to access url using `page.url`

Answer №2

Utilize a for loop (outside of its block) to loop through the JSON variable containing your URLs

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

Modifying elements within a JSON array-generated list

As a beginner in JavaScript, I have encountered an issue with my code. It dynamically creates a list from a JSON array called rolesData and displays the data from "roles" in a list based on a random selection (using document.body.appendChild(createList(rol ...

Storing JSON data retrieved from a fetch API request in a JavaScript global variable - a beginner's guide

I have been experimenting with the fetch API and successfully managed to log the fetched data to the console using the then() method. However, I am struggling to store this data in a global variable for later use in vanilla javascript due to the nature of ...

Storing persistent JSON data in a mobile app built with HTML5 involves utilizing the local storage capabilities of the

I am currently working on a mobile app using PhoneGap that is based on HTML technology. When the app is opened for the first time, my goal is to have it download a zip file that includes a JSON file and media files such as images or audio. Once the zip f ...

What is the best way to solve the problem of Chrome auto-complete overlapping with labels in Vuetify?

When attempting to make a login form using outlined text fields in Vutify, there is an issue with Chrome autocomplete overlapping the labels. <v-text-field v-model="email" label="e-mail" name="email" outlined prep ...

Retrieving a particular value from an array received through Ajax in JavaScript

Ajax functionality $("#panchayat").change(function(){ var param = {'panchayat_id':$(this).val()}; alert (param['panchayat_id']); $.ajax({ type : 'POST', url : '<?php echo base_url();?>index.php/parent_taluk' ...

Creating a dynamic text field integrated with Google Places in Ionic 4: a step-by-step guide

I am currently implementing the google-place-api autoComplete feature in my project, but I encountered an error: TypeError: Cannot read property 'getInputElement' of undefined .html <section [formGroupName]="i" *ngFor="l ...

Using Angular to make GET requests with JSON data in PHP

Seeking assistance with connecting Angular frontend to PHP backend. Upon calling the service, I am receiving an empty array in the console. Controller: angular.module('pageModule') .controller('pageController', ['$scope', &a ...

Define a new type in Typescript that is equal to another type, but with the added flexibility of having optional

I have 2 categories: category Main = { x: boolean; y: number; z: string } category MainOptions = { x?: boolean; y?: number; z?: string; } In this scenario, MainOptions is designed to include some, none, or all of the attributes that belong to ...

Troubleshooting the issue with reactdom.render() functionality in CodeSandbox

Having issues with ReactDom in CodeSandbox for React. The HTML file includes: <body> <div id="root"></div> </body> <script src="scr/index.js"> The JavaScript file (named index) includes: ReactDOM.rende ...

Are you utilizing content loaded through jquery load in your work?

I have successfully utilized jQuery's .load() function to retrieve the contents of a table from another webpage and insert it into the current page, which is functioning properly. However, when I try to run scripts afterwards that manipulate the newly ...

Updating the filter predicate of the MatTableDataSource should allow for refreshing the table content without needing to modify the filter

Currently, I am working on dynamically altering the filterPredicate within MatTableDataSource to enhance basic filtering functionalities. I want to include a fixed condition for text filtering (based on user input in a search field) for two string columns ...

Executing Laravel Ajax Requests on the whole website

I have been encountering an issue with my Ajax post call in my application. The call is supposed to update the Navigation throughout the entire site, but it seems to be working on some pages and not others. I am looking for a way to fix this and make it mo ...

What is the best way to incorporate a mute/unmute button into this automatically playing audio?

Seeking assistance in adding a mute button for the background sound on my website. Can anyone provide guidance on how to achieve this? Below is the HTML code responsible for playing the sound: <audio id="sound" autoplay="autoplay" ...

Guide: Implementing Vuex store within a plugin

I recently developed a custom Vue plugin which includes a customized instance method import Echo from 'laravel-echo'; import Vue from 'vue'; import config from '@/config'; const echor = { install(Vue){ Vue.prototy ...

What are the variances in using xpath with selenium webdriver?

WebElement element4=driver.findElement(By.xpath("/html/body/div/table/tbody/tr[2]/td[2]/div/div/div/div[4]/ul/li[3]/a")); WebElement element3=driver.findElement(By.xpath("//*[@id='nav_cat_3']")); When retrieving xpaths using firebug, both xpath ...

What is the best way to send pg-promise's result back to the controller in Express?

While working with Ruby on Rails (RoR), I am familiar with the MVC (Model-View-Controller) concept. In this framework, the controller is responsible for receiving data from the model, processing it, and rendering the view. An example of this structure look ...

When implementing tooltips in Apexchart's JavaScript, the y-axis second does not appear in the chart

Typically, when I append data to the second y-axis as an array, it works perfectly. However, for some reason, when I try to append a collection to the data, it no longer shows with two y-axes simultaneously. I even tried adding x and y as the Apex documen ...

Await keyword cannot be used due to undefined object reference

Currently in the process of implementing authentication into my node API. Using PassportJS, although I am fairly new to this so please bear with me. The goal is to add a local strategy and verify the user's password during login: // Local Strategy ...

What could possibly be the reason for this not returning null?

Consider this JavaScript snippet: var value = parseInt(""); console.log(value != Number.NaN ? value : null); Why does the console output Nan instead of null? Is there a way to modify the code so that it actually returns a null value? I attempted to wra ...

The absence of parameters in the Express.js middleware object

const application = express(); let routerInstance = require('express').Router({mergeParams: true}); const payloadMiddlewareFunction = (request, response, next) => { console.log('A:', request.params); const {params, query} = reque ...