Obtain element values using Protractor and WebDriverJS and store them in an array of objects

Coming from a Java+WebDriver background, I am new to Protractor, WebdriverJS, and Jasmine. In the image displayed, my goal is to hover over all bubbles and retrieve the tool tip values (city, sold, connected), assign them as objects to an array, and return it to the calling function. Could someone guide me on how to achieve this - creating an array of objects in this particular scenario? I am looking to assert it from my spec file.

Upon calling this function, return arr; executes before the remaining code, likely due to its asynchronous nature.

this.getSalesVolumeDistribution = function() {
var arr = [];
var icons = element.all(by.css('#map-container svg>circle'));
icons.map(function(elm) {
        browser.actions().mouseMove(elm).perform();
        var toolTipCity = element(by
            .css('#map-container g.highcharts-tooltip tspan:nth-of-type(2)'));
        var toolTipUnitsSold = element(by
            .css('#map-container g.highcharts-tooltip tspan:nth-of-type(3)'));
        var toolTipUnitsConnceted = element(by
            .css('#map-container g.highcharts-tooltip tspan:nth-of-type(4)'));

        toolTipCity.getText().then(function(text) {
            var cityVal = text.replace('City: ', '').replace(',', '');
            console.log(text.replace('City: ', '').replace(',', ''));
            var soldVal = toolTipUnitsSold.getText().then(function(text) {
                return text.replace('Units Sold: ', '').replace(',', '');
            });
            var connVal = toolTipUnitsConnceted.getText().then(function(text) {
                return text.replace('Units Connected: ', '');
            });

            arr.push({
                city: cityVal,
                sold: soldVal,
                conn: connVal
            });

            });
    });
return arr;
};

https://i.sstatic.net/YgZvr.jpg

Answer №1

Ensure to retrieve the outcome of map(), which will result in a promise resolving to an array of objects:

this.getSalesVolumeDistribution = function() {
    var icons = element.all(by.css('#map-container svg>circle'));

    // MODIFICATION MADE HERE v
    return icons.map(function(elm) {
        browser.actions().mouseMove(elm).perform();
        var toolTipCity = element(by
            .css('#map-container g.highcharts-tooltip tspan:nth-of-type(2)')).getText();
        var toolTipUnitsSold = element(by
            .css('#map-container g.highcharts-tooltip tspan:nth-of-type(3)')).getText();
        var toolTipUnitsConnceted = element(by
            .css('#map-container g.highcharts-tooltip tspan:nth-of-type(4)')).getText();

        // MODIFICATION MADE HERE v
        return protractor.promise.all([toolTipCity, toolTipUnitsSold, toolTipUnitsConnceted]).then(function(tooltips) {
            var cityVal = tooltips[0].replace('City: ', '').replace(',', '');
            var soldVal = tooltips[1].replace('Units Sold: ', '').replace(',', '');
            var connVal = tooltips[2].replace('Units Connected: ', '');

            // MODIFICATION MADE HERE v
            return {
                city: cityVal,
                sold: soldVal,
                conn: connVal
            };
        });
    });
};

Pay attention to where I've placed the return statements (marked with comments). Also, take note of the usage of protractor.promise.all() to handle multiple promises for the tooltip texts.

If you need to validate the function's output, enclose it within an expect() statement - this action will automatically resolve the promise and execute the assertion, for example:

expect(myPageObject.getSalesVolumeDistribution()).toEqual([
    {city: 'El Paso', sold: '344', conn: '321'},
    {city: 'New York', sold: '500', conn: '600'}
]);

Answer №2

In protractor, utilizing the map function allows you to generate an array of values that can be returned. You can find more information about this functionality at this link

Instead of manually pushing values onto an array, you can simply use the following code snippet for a cleaner approach: return { city: cityVal, sold: soldVal, conn: connVal }

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

Are there any comparable features in Angular 8 to Angular 1's $filter('orderBy') function?

Just starting out with Angular and curious about the alternative for $filter('orderBy') that is used in an AngularJS controller. AngularJS example: $scope.itemsSorted = $filter('orderBy')($scope.newFilteredData, 'page_index&apos ...

What is the procedure for closing a snackbar when the close button is clicked?

I am having trouble closing a snackbar when the close button is clicked. The snackbar should initially pop up on page load and only close when manually triggered. I have set the timeout to zero, but the snackbar does not close when the close button is clic ...

Changing the theme of a toggle button in Jquery Mobile when the button is pressed

I have a group of buttons with a specific class <div class="prog-day"> <div class="prog-clear" data-role="controlgroup" data-type="horizontal> <a href="#" data-role="button" data-mini="true" data-theme="b">Clear</a> ...

Multiple occurrences of setting the state on an array result in logging an empty array each

My current challenge involves fetching data from a backend server and storing it in an array. However, when I attempt to pass this array to another component, I encounter an issue where multiple empty arrays are being passed instead of one filled with data ...

Failure to successfully transmit data from Ajax to PHP script

When I click on a button in my HTML page, I am trying to retrieve information from my PHP code, but it is not connecting properly. The front page displayed in index.php is as follows: <!DOCTYPE html> <html> <head> <link rel="styleshe ...

Are You Able to Develop a Floating Window That Stays Persistent in JavaScript?

Looking to create a persistent floating window in a NextJS 14 app. This window needs to remain on top, even when navigating between browser windows. Want it to stay visible even when the browser window is minimized, like a Picture-In-Picture feature. Mos ...

Sorting alphanumeric strings in React Bootstrap Table Next on a dynamic table

I am facing an issue with sorting columns in a dynamic table with over 70 columns using React-Bootstrap-Table-Next. The problem arises when trying to sort the columns in alphanumerical order, as some columns contain numbers and others contain letters. The ...

Having issues with getting Bootstrap to function properly in my create-react-app

I've been attempting to use traditional Bootstrap instead of react-bootstrap to render my React component, but I can't seem to get it right. I've installed Bootstrap via npm and included the CDN links and scripts as well. Despite trying vari ...

"Implementing filtering logic for an array of objects with multiple conditions in a React application

I am looking to apply filters to a person list based on criteria such as city, job, age, and gender. How can I apply filters based on five conditions in React? I tried using filter chaining but it did not work for me. In the useEffect hook, I applied indiv ...

Enhance the database with partial updates using the patch method in Django Rest Framework

I have a model called CustomUser that extends the AbstractUser class. class CustomUser(AbstractUser): detail = models.JSONField(default=dict) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=Tr ...

"Despite the successful execution of the PHP script, the error function in the Ajax POST request

I am working on developing a mobile app using jQuery, jQuery Mobile, and HTML with PhoneGap. I have successfully implemented AJAX to call PHP scripts on the server for tasks like updating, inserting data, and sending emails. However, I consistently encoun ...

Deciphering JSON strings using JavaScript

Here is a string that I am trying to parse using Json: {\"description\": \"PSY - Gangnam Style (\\uac15\\ub0a8\\uc2a4\\ud0c0\\uc77c) \\n\\u25b6 NOW available on iTunes: h ...

Is it possible to upload a file using Angular and ASP.NET Web API Core?

I am encountering an issue with CORS policy while making requests. It works fine when the content-type is set to 'application/json'. However, when I try to upload a file using content-type 'multipart/form-data', I receive an error: XML ...

Three.js - Optimizing and Handling Images - Best Practices

My current project has a unique concept: https://i.sstatic.net/Jd3Ot.jpg The main idea revolves around a virtual room that dynamically adjusts its height based on the number of images loaded by the user. While it functions smoothly with fewer pictures, ...

Why is the error message "Invalid field name: '$conditionalHandlers' in 'collaborators..$conditionalHandlers'" popping up now?

Currently, in my Node/Express/Mongoose application (latest versions), I am working on a feature that involves "Projects" with a list of "collaborators" identified by the IDS of "Users". To simplify complex aggregations, I have decided to store these IDS as ...

developing a custom modal using a button in a React project with Material UI

Hello everyone, I have a question regarding React. I am fairly new to React and need some assistance with adding a new function that creates a Modal. I want to call this function onClick when the add icon is pressed (line 43). Any help would be appreciated ...

Avoiding the backslash in JavaScript

<script type="text/javascript"> console.log(#Fileurl#); jQuery.ajax({ url: "http://xyz:8800/aaa/bbb/ccc", type:'POST', dataType: 'JSON', data:{"file":"#Fileurl#"}, success: function ...

Modifying the sidebar navigation in Ionic for a user who is logged in

Is it possible to modify the side menu content based on whether a user is logged in or not? Example 1 - user not logged in: If a user isn't logged in, this side menu will be displayed. https://i.stack.imgur.com/iY427.png Example 2 - user is logged ...

Move a <div> using a handle (without using JQuery)

I devised a plan to create a moveable div with a handle and came up with this code snippet: var mydragg = function() { return { move: function(divid, xpos, ypos) { divid.style.left = xpos + 'px'; divid.style.top = ypos + &apo ...

What is the process for invoking a server-side C# method from AJAX while transmitting parameters to the function using CommandArgument?

My C# method is responsible for saving data to a SQL Server. It is called from an Onlick event, passing parameters using CommandArgument. Here is an example: <asp:LinkButton runat="server" onClick="save" CommandArgument='<%# Eval("post_id").ToS ...