Discover the elements with Protractor, cycle through the total number of located elements, and proceed to press the button

Trying to figure out how to click a button multiple times based on the number of elements found with a specific classname. If there are 3 elements found, the button should be clicked 3 times.

The current approach:

(Update at the bottom)

The total count of btn btn-remove btn-outlined elements in the HTML can vary, so I tried to read this count first and then loop through that many times to click the button accordingly.

The issue I'm facing is that although it correctly identifies the number of elements (e.g., 3), the loop seems to be skipping the necessary it functions inside for some unknown reason.

Here's where it goes wrong:

      it('Click remove button - ' + i + '/' + text.length, function (done) {

            browser.driver
                .then(() => browser.executeScript("arguments[0].click();", element.all(by.className('btn btn-remove btn-outlined').first().getWebElement())));
                .then(() => done());
        });

        it('Wait for fading button to be gone', function (done) {

            setTimeout(function () {
                done();
            }, 1000);

        });

I suspect there might be an error that I'm overlooking. How do I determine the number of specified elements in the DOM and iterate through them while clicking on the remove button?

EDITED CODE:

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

    element.all(by.className('btn btn-remove btn-outlined')).getText().then(function (text) {
        console.log(text.length) //returns 3
        for (var i = 0; i < 4; i++) {

            console.log(i); //Prints 0, 1, 2

            it('Click remove button - ' + i + '/' + text.length, function (done) {

                console.log("Remove button"); //Doesn't print

                browser.driver
                    .then(() => browser.executeScript("arguments[0].click();", element.all(by.className('btn btn-remove btn-outlined').first().getWebElement())));
                    .then(() => done());
            });

            it('Wait for fading button to be gone', function (done) {

                console.log("Timeout"); //Doesn't print

                setTimeout(function () {
                    done();
                }, 1000);

            });
        }
    })
    done();
});

Answer №1

The issue with the it inside the for loop not being executed is due to its dynamic generation at runtime, which is not recognized by test frameworks like Jasmine and Mocha.

According to my understanding, Jasmine requires static it statements in test script files to be loaded and parsed before execution. Any dynamically generated it statements after this stage will be ignored. Therefore, it is necessary to remove dynamic it.

Consider using the following code:

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

    let allBtns = element.all(by.className('btn btn-remove btn-outlined'));

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

        console.log('Find buttons:', cnt)

        for (let i = 0; i < cnt; i++) { // make sure to use let instead of var here.
            console.log('Remove button - ' + i + '/' + cnt);
            browser.executeScript("arguments[0].click();", allBtns.get(i).getWebElement())
            browser.sleep(1000) // sleep for 1 second
        }
    })
    .then(()=>{
        done();
    })

});

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

JSON Generator's date formatting convention

One method I use to create a JSON object is through JSON-GENERATOR I prefer the date to be formatted like this: 2017-12-31 [ '{{repeat(5, 7)}}', { equityPriceList: [ { date:'{{date(new Date(1970, 0, 1), new Date(),[DD ...

JavaScript, PHP handlers, and CommentBox all work together seamlessly to create

$("#login").click(function(){ $.getJSON("handlers/Login.php?name="+$("#username").val(), function(data){ console.log(data); //retrieves data from login box and sends it to the handler, returning a JSON array }); template = $("#hid ...

Prevent event listeners from being triggered during the '$destroy' event. Error: $on function is undefined

As I attempt to halt all event listeners when the scope is destroyed, a certain error arises. The following error is displayed: TypeError: vm.$on is not a function; Even using vm.on(..) does not resolve the issue angular.module('app.layout&apo ...

Passing props through Link in React can be a tricky process, especially when encountering issues with undefined props like this

My latest project involves creating a recipe research tool in react. The homepage features buttons that allow me to search for recipes and view them based on the data I gather. However, when I try to access the state values using 'console.log(this.pro ...

Step-by-step guide on triggering a button using another button

I have a unique question that sets it apart from others because I am looking to activate the button, not just fire it. Here is my syntax: $("#second_btn").click(function(){ $('#first_btn').addClass('active'); }) #first_btn ...

What is the best way to toggle the readonly attribute on an input within an ng-repeat row when a button is clicked?

Here is some HTML content: <!---- HTML Content ----> <div class="container-fluid" ng-app="myApp"><br> <div class="row" ng-controller="mainController"> <div class="col-md-12"> <div class="panel pa ...

Tips for transferring a value from a function in ASPX to a CS file

I seem to be overlooking a small detail. I have a dropdown list (DDL) and a function in my C# file. I want to pass the 'value attribute' of a selected DDL option to my function, but I can't seem to retrieve the value attribute. I checked the ...

Python For Loop and Recursion Running into Selenium Error

My goal is to use Selenium to iterate through a list of strings and search each element in the list using Google Chrome. Below is the code I have written, utilizing recursion: from selenium import webdriver from selenium.webdriver.common.keys import Keys ...

terminate server through the router

I have created an express application like the following: const express = require('express') const app = express(); app.use(express.static(path.join(__dirname, 'public'))); app.post('/close', async (_, res) => { res.sta ...

Separate the selected option in the TEXTAREA by commas to make it easier to

Can you assist me with integrating this example? I have the following elements: When adding a textarea, I require an option to be selected and separated by a comma. For instance: Here I will select an option: Subsequently, this chosen option must be ad ...

Guide on retrieving the inner text of a specific web element through Selenium and VBA: Seeking assistance for troubleshooting

I am encountering an issue extracting the inner text of a web element on this specific page (Utilizing VBA + Selenium): The target is to retrieve the text ("20°") from the following element: <div class="temperature" style="">20 ...

The information returned to the callback function in Angular comes back null

In my Node.js application, I have set up an endpoint like this: usersRoute.get('/get', function(req, res) { //If no date was passed in - just use today's date var date = req.query.date || dateFormat(new Date(), 'yyyy-mm-dd&ap ...

Need assistance with jQuery AJAX?

Hey there, I'm a new member and I've gone through the different Ajax Help topics but still can't figure out why my code isn't working. Here's what I have: $(document).ready(function(){ $.ajax({ type: "GET", ur ...

Guide on dismissing Chrome's save password prompt using Python

How can I close the save password prompt window in Chrome when I am unable to gain control over it? I have attempted using Xpath, selenium.webdriver.chrome.options (by adding arguments). I have also tried: alrt = driver.switch_to_alert() alrt.dismiss() ...

Generate seamless rotation within a specified time frame (+- x%)

I need to rotate a cube in my scene with a specific initial speed within a specified timeframe. The end angle of the cube must match the starting angle. To account for potential variations, I am allowing for a deviation of up to 5% in the timeframe. Cu ...

Guide to Re-rendering a component inside the +layout.svelte

Can you provide guidance on how to update a component in +layout.svelte whenever the userType changes? I would like to toggle between a login and logout state in my navbar, where the state is dependent on currentUserType. I have a store for currentUserTyp ...

I'm encountering an issue while attempting to execute this code, receiving an error stating "AttributeError: 'WebDriver' object does not possess the attribute 'find_element_by_name'."

Having trouble with this code, getting an attribute error driver: WebDriver = webdriver.Chrome("C:\Drivers\chromedriver_win32\chromedriver.exe") driver.get("https://opensource-demo.orangehrmlive.com/") driver.find_element_by_name("txtUsern ...

.then function not functioning properly in Axios DELETE request in a React project

I am currently facing an issue with calling a function to update the array of notes after deleting a note from the database. The function causing the error is called deleteNote, and the function I intend to call within the .then promise is getNotes. Here i ...

Even though I have successfully compiled on Heroku, I am still encountering the dreaded Application Error

Looking for help with a simple express/node application to test Heroku? Check out my app.js: const express = require('express') const app = express() const port = '8080' || process.env.PORT; app.get('/', function (req, res) ...

Implement Dynamic Filters in a Vue Component

How can filters be programmatically applied to select values? During each iteration of records and columns, I am checking if the column ID starts with 'd', indicating it's a datetime field. In such cases, I want to apply the humanize filter ...