Ways to interpret element values and choose the number of clicks

Currently, I am focusing on parsing elements where the tag might contain the word "example". Here is an example snippet of code that I am working with:

<div class="stock-controller" style="transition: border-bottom 0.3s ease 0s, opacity 0.3s ease 0s;">
    <div class="message">
        <svg width="14" height="14" viewBox="0 0 14 14">
            <g fill="none" fill-rule="evenodd">
                <path fill="#E00751" d="M14 7A7 7 0 1 1 0 7a7 7 0 0 1 14 0z"></path>
                <path fill="#FFF" fill-rule="nonzero" d="M8.45 7.036L10.414 9 9 10.414 7.036 8.45 5.07 10.414 3.657 9l1.964-1.964L3.5 4.914 4.914 3.5l2.122 2.121L9.156 3.5l1.415 1.414L8.45 7.036z"></path>
            </g>
        </svg>Sorry, we only have 10000 of this product.</div> //Need to read here how many available products
    <div class="quantity-input invalid">
        <button class="btn left" aria-label="Decrease"> //How many users have chosen - how many are in stock = number of clicks required.
            <svg class="svg-icon" viewBox="0 0 24 24">
                <path fill-rule="evenodd" d="M7 11h10v2H7z"></path>
            </svg>
        </button>
        <input type="number" pattern="[0-9]*" min="0" max="10002" value="10002"> //Need to read how many we have chosen
        <button class="btn right" aria-label="Increase" disabled="">
            <svg class="svg-icon" viewBox="0 0 24 24">
                <path fill-rule="evenodd" d="M13 17v-4h4v-2h-4V7h-2v4H7v2h4v4z"></path>
            </svg>
        </button>
    </div>
</div>

https://i.sstatic.net/o68UH.png

Essentially, there are three elements to consider. First, we need to determine the quantity of products in stock (in this instance, it's 10000). Second, we must ascertain the number of items a user has selected, which is 10002. Therefore, we would need to calculate 10002 - 10000 = The amount of times to click the

<button class="btn left" aria-label="Decrease">
.

Thus far, I have worked on:

it('Check decrease button', function (done) {

    let allBtns = element.all(by.className('stock-controller'));

    element.all(by.className('stock-controller')).each(function (element, index) {
        // This will output: Sorry, we only have 4 of this product., Sorry, we only have 10000 of this product.
        element.getText().then(function (text) {
            console.log(index, text);
        });
    });

    allBtns.count()
        .then(function (countElement) {

            console.log('Find decrease buttons: ', countElement)

            //for (let i = 0; i < countElement; i++) { 
                //browser.executeScript("arguments[0].click();", allBtns.get(i).getWebElement())
                //browser.sleep(1000) // sleep for 1 second
              //}
        })
        .then(() => {
            done();
        })

});

Another issue arises when there are multiple instances of 'stock-controller'. For instance, there could be 5 'stock-controllers' each containing different quantities of products in stock and selected by the user.

Therefore, my query is as follows:

How can I determine the number of 'stock-controllers' present and subsequently calculate the requisite number of clicks for the decrease button for each 'stock-controller'?

The functional code is displayed below:

it('Clicked all decrease buttons', function (done) {

    let allProds = element.all(by.css('div.stock-controller'));

    allProds.count()
    .then(function (cnt) { 

        for(let index=0;index<cnt;index++) {

            let section = allProds.get(index),

                stock_qty_str = section.element(by.css('div.message')).getText(),
        
                user_qty_str = section.element(by.css('input[type="number"]')).getAttribute('value'),
               
                btn_dec = section.element(by.css('button[aria-label="Decrease"]'));

            Promise.all([stock_qty_str, user_qty_str])
                .then(function(data){
                    
                    let group = data[0].trim().match(/^Sorry.*?(\d+)/)

                    if(group) {
                        let stock_qty = group[1] * 1,
                            user_qty = data[1].trim() * 1,
                            
                            gap = user_qty - stock_qty;

                        for (let i = 0; i < gap; i++) {
                            browser.executeScript("arguments[0].click();", btn_dec.getWebElement());
                        }
                    }
                })
        }

    })
    .then(()=>{
        done();
    })

});

Answer №1

Here is a code snippet with an explanation included:

it('Click remove button', function (done) {

    let allProducts = element.all(by.css('div.stock-controller'));

    allProducts.count()
    .then(function (count) { // number of products

        for(let index=0;index<count;index++) {

            let section = allProducts.get(index),

                // extracting stock quantity from the message string
                stock_qty_str = section.element(by.css('div.message')).getText(),
                // getting user inputted quantity 
                user_qty_str = section.element(by.css('div.quantity-input input'))
                                      .getAttribute('value'),
                // selecting the Decrease button
                btn_dec = section.element(by.css('button[aria-label="Decrease"]'));

            Promise.all([stock_qty_str, user_qty_str])
                .then(function(data){
                    // using RegExp to parse the stock quantity
                    let group = data[0].trim().match(/^Sorry.*?(\d+)/)

                    if(group) {
                        let stock_qty = group[1] * 1,
                            user_qty = data[1].trim() * 1,
                            gap = user_qty - stock_qty; // determine how many times Decrease button should be clicked

                        for(let i=0;i<gap;i++) {
                            btn_dec.click();
                            browser.sleep(1000).then(function(){
                                console.log('Click Decrease button: ' + i + '/' + gap)
                            })
                        }
                    }
                })

        }

    })
    .then(()=>{
        done();
    })

});

Answer №2

I'm not a fan of using protractors, but when working with Java I typically create a list of WebElements using XPath like //div[@class='stock-controller']

After that, I iterate through each stock-controller, read the amount to click, and then proceed to click on it.

Pseudocode:
    List stockcontrollers = findby.xpath(//div[@class='stock-controller')
foreach(item in stockcontrollers)
{
get.item
read amount to click
for(x<amount to click)
{click}
}    

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

How can JavaScript generate arrays filled with randomly generated numbers?

As part of a classroom assignment, I am working on creating a table using only Javascript. The table is set up perfectly, except that every other row displays a random number before moving on to the next row. How can I eliminate this random row? var ta ...

Implementing Date.now() as a Schema Field Type in Meteor's Simple-Schema

Within my Meteor application, I have utilized Date.now() to generate a timestamp for inclusion in a new MongoDB document. Although Date.now() appears to be an appropriate choice for my app, I lack expertise in managing dates and times. As I transition to ...

Display Vue component depending on specified attribute

I have a block of code that I am working with: <div> <b-card no-body> <b-tabs pills card vertical no-key-nav v-model="step"> <b-tab title="Subject" v-for="animal in animals" :key="animal&q ...

The combination of spring, cucumber, and Selenium's fluent wait is causing my driver

I am attempting to implement fluent wait in my code @Component @Scope(SCOPE_CUCUMBER_GLUE) public class UserCreationPageImpl extends BaseBinariosPage implements UserCreationPage { Wait<WebDriver> wait = new FluentWait<WebDriver>( driver ) ...

Guide on implementing a redirect to a different page following form submission with the inclusion of a loading screen

<form action='page.html' method='post'> <input type="text" name="name" placeholder="Enter your name here"> <input type="submit" value="submit"> </form> The cod ...

Troubles with IE7 regarding jQuery [clicking and changing events]

My code snippets are designed to loop through cached JSON data on the 1st click function and display any values that exist for a specific id. The 2nd change function captures when elements' values change (e.g., from yes to no). Since these elements a ...

Add one string to an existing array

I have a component named ContactUpdater that appears in a dialog window. This component is responsible for displaying the injected object and executing a PUT operation on that injected object. The code for the component is shown below: HTML <form [for ...

Retrieve all information contained within the HTML tags <div align="center"></div> using Java programming

I am new to Java and feeling a bit overwhelmed since I have no experience with it. With Selenium, I was able to download the HTML of a page and store it in a string. Now, my goal is to extract all the data between <div> tags and populate an array wit ...

"Need help passing an API key in the header of a Vue.js project? I recently encountered this issue while using a

How can I include an API key in the header of a Vue.js request? I am using DRF pagination. methods: { getPostData() { axios .get("http://192.168.43.126:8000/api/?page=" + this.currentPage, { headers: { &q ...

Using a CSS style to modify a class based on another class at the same level in the hierarchy

I am working with a jQuery carousel that is adding an 'active' class to images within a div. Within the same div, there is also a span with a 'fade' class that has a CSS style of opacity: 0. Is there a way to change the CSS style of the ...

Transferring dynamic parameters from a hook to setInterval()

I have a hook that tracks a slider. When the user clicks a button, the initial slider value is passed to my setInterval function to execute start() every second. I want the updated sliderValue to be passed as a parameter to update while setInterval() is r ...

Angular directives do not recognize HTML tags as elements but rather treat them as plain text

Let's consider this scenario: There is a function called foo() in my controller: $scope.getOffers = function(){ var txt1 = "aaaa" + "<br>" + "bbbb"; $scope.newData = txt1; }; Here is the relevant HTML snippet: <div class="help-b ...

Utilizing Typescript Generics in Arrow Function to Combine Two Arguments

For instance, I am working with this code in a .tsx file extension const Add = <T,>(arg0: T, arg1: T): T => arg0 + arg1; const A = Add(1, 2); const B = Add('1', '2') However, I am encountering an issue, as there is an error m ...

Replicating a row in a table without disrupting a button within the row

As a novice in the world of coding, I am currently embarking on a project to revamp an existing website. The task at hand involves creating a table with a built-in save/edit feature, which I have successfully implemented. However, I am facing a roadblock w ...

Validating an array of IDs against a different model in Mongoose/MongoDB

Exploring Two Moongose Schemas: var Schema2 = new Schema({ founder : { type: String, ref: 'User'}, schema_name : [{ type: String}], }); var Schema1 = new Schema({ creator : { type: String, ref: 'User'}, schema_ref : [{ ...

Experimenting with a function that initiates the downloading of a file using jest

I'm currently trying to test a function using the JEST library (I also have enzyme in my project), but I've hit a wall. To summarize, this function is used to export data that has been prepared beforehand. I manipulate some data and then pass it ...

display images fetched from a PHP/MySQL database in a jQuery dialog box

UPDATE: A solution has been found and the code has been updated accordingly. Currently, I have the images stored in a directory on my local system where I am hosting an IIS server. I am able to retrieve these images successfully and display them using the ...

What steps do I need to take to grant authorization to chromedriver.exe?

While working on my face recognition project using Chrome driver, I encountered an issue in the 4th line of code below. How can I resolve the permission error for chromedriver.exe? code: data_path = '/content/drive/MyDrive/FaceRecognition/faces' ...

XDomainRequest for cross-domain ajax is throwing an error that is difficult to understand - an empty error message

Here is my AJAX call to a page on a different domain: if ($.browser.msie && window.XDomainRequest) { // Use Microsoft XDR var xdr = new XDomainRequest(); xdr.open("post", "https://different-domain.aspx"); ...

What is the best way to display data from a dynamically generated table in a popup window?

My table is dynamically populated with the following JavaScript code: $(document).ready(function (e) { var t = { Qty: [61.0, 0.0, 8.0], Name: ["2009 A", "2009 B", "2009 C "] } $.each(t.Qty, function (i, ele) { $("#content") ...