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

Running a Blitz.js api handler triggers a Google Cloud Storage call failure with the message "error:0909006C:PEM routines:get_name:no start line"

When attempting to utilize @google-cloud/storage within a Blitz.js /api handler, I encounter the following error: error:0909006C:PEM routines:get_name:no start line at Sign.sign (internal/crypto/sig.js:110:29) at NodeCrypto.sign (C:\Users&bsol ...

Out of the box, Next.js is equipped with a standard error message stating: "TypeError: Cannot read properties of null (reading 'useContext')"

After just setting up next.js for my upcoming website, I ran into some unexpected errors while trying to host it with "next". The specific error message I encountered was: TypeError: Cannot read properties of null (reading 'useContext') This iss ...

AngularJS - Textarea not resetting content on ng-click event

Having an issue with my textarea. When attempting to clear it using ng-click, nothing happens... Can anyone provide assistance? Here is my code for testing: My app If you prefer to view it here: HTML : <div ng-controller="Ctrl1"> <d ...

Tips for transferring data from the Item of a repeater to a JavaScript file through a Button click event for use in Ajax operations

I am working with a repeater that displays data from my repository: <div class="container" id="TourDetail"> <asp:Repeater ID="RptTourDetail" runat="server" DataSourceID="ODSTTitle" ItemType="Tour" EnableViewState="false" OnItemDataBound="Rp ...

When utilizing a Javascript event listener within ReactJS with NextJS, the dynamically imported module without server-side rendering fails to load

Hello everyone, I am new to ReactJS and NextJS and would really appreciate some advice on the issue below. Thank you in advance! Here is my current tech stack: Node v16.6.1 React v17.0.2 Next.js v10.0.4 I'm working on implementing a carousel and si ...

Using jQuery to toggle the visibility of a group of radio buttons causes the div to quickly appear and disappear

My code is working perfectly as it shows up when needed and disappears when necessary. The concept behind this form is that the user can check a box, view more required form data related to the checked item, make those fields required, and then uncheck the ...

Is it possible for me to include additional fields in a vuetify calendar event?

Is there a method to incorporate additional fields, such as a description, in addition to the name and start/end time for an event on the v-calendar's day view? ...

What is the process for consumers to provide constructor parameters in Angular 2?

Is it possible to modify the field of a component instance? Let's consider an example in test.component.ts: @Component({ selector: 'test', }) export class TestComponent { @Input() temp; temp2; constructor(arg) { ...

The directive in an Angular app is not loaded due to lazy loading

Seeking assistance with lazy loading a directive in my Angular application, I am using ui.router and oc.lazyLoad. Below is the code snippet: menu : <ul> <li><a ui-sref="home">Home</a></li> <li><a ui-sre ...

Begin the process of setting up PDF.js on the website

I've been attempting to incorporate PDF.js into my website, but I'm struggling to do it correctly. When I try to display the PDF file on the screen, I encounter this issue: Although I can't see the PDF file on the screen, when I click on P ...

Managing toggles for save and edit buttons in Vue - a comprehensive guide

I am currently working on a Vue 'app' within a larger Django application as a means to enhance my understanding of Vue. My objective is to create unique forms that can be edited independently. I have been experimenting with this for some time n ...

Retrieve JSON data within a service and provide it to a component

I am currently facing an issue with loading data from a JSON file into my component using a service. The data is successfully loaded in the service, as confirmed by the console log; however, when trying to access the data in the component, it does not disp ...

The content of the text does not align. Alert in React 16

Currently, I am working on developing a ReactJs application with server-side rendering. Here are my entry points for both the client and server: client.jsx const store = createStore(window.__INITIAL_STATE__); hydrate( <Provider store={store}> ...

What is the best way to insert an iframe using getElementById?

I am looking to make some changes in the JavaScript code below by removing the image logo.png lines and replacing them with iframe code. currentRoomId = document.getElementById('roomID').value; if ( document.getElementById('room_' + c ...

The function in jQuery that can be used to hide a <div> when clicked

I am facing a problem with my jQuery code that is supposed to remove/hide a specific div. Despite checking various examples, I can't seem to make it work properly. This issue arises in the context of jQuery on Drupal 7. The live site where this proble ...

How to Troubleshoot VueJS Component Render Issues After Importing/Calling Components

In one of my projects, I successfully implemented a file uploader component using import and component statements. import fileUploader from '../common/FileUploader.vue'; Vue.component('file-uploader', fileUploader); This implementation ...

Working with scrollIntoView in useEffect (Encountering an error trying to access 'scrollIntoView' property of null)

Starting from scratch, I'm working on setting up my webpage and crafting some code. function BasicDetails() { React.useEffect(()=>{ scrollView(); }, []); function scrollView() { document.getElementById('main-root& ...

Pause the audio using jQuery when the slide changes

I have a Drupal website with a slider that includes an audio player on each slide. I need the audio to stop whenever the slide changes. The slider plugin I'm using is owlCarousel. Here is my current code: $("#owl-demo").owlCarousel({ afterAction: ...

Exploring the possibilities of jQuery with Accordion functionality and creating dynamic multiple menus

Incorporating the Wayfinder and Accordion menus, I have set up a two-level menu structure for the left column. The structure looks like this: <ul class="accordion">: Menu 1 Sub-menu 1.1 Sub-menu 1.2 Sub-menu 1.3 Menu 2 Sub-menu 2 ...

Using AngularJS location.path for unique custom URLs

Control Code: $scope.$on('$locationChangeStart', function () { var path = $location.path(); var adminPath = '/admin/' ; if(path.match(adminPath)) { $scope.adminContainer= function() { return true; }; }); HTML <div clas ...