Proper techniques for storing element count in Protractor


I am a beginner when it comes to using Protractor and I am not entirely satisfied with the code snippet below, even though it is functional.
My goal is to store the count in a variable (named "nb_before") and use it later on. However, due to the promise mechanism in place, I find it difficult to achieve concisely. This led me to cram everything into a single function, resulting in quite an ugly piece of code.
Could it be that I am overlooking something crucial?
Warm regards

    // The purpose here is to count the lines, click a button to add a new line,
    // and then confirm that the new line contains a specific text.

    it("Test Case", function () {
        browser.get(browser.baseUrl);
        var button = element(by.xpath("//whatever"));
        var rows = element.all(by.xpath("//whatever"));
        rows.count().then(function(count){
            nb_before = count;
            button.click(); // adds a line
            var nb_after = nb_before + 1;
            var new_line = element(by.xpath("//li[" + nb_after + "]"));
            expect(new_line.getText()).toEqual("yay");
        });
    });

Answer №1

It appears that utilizing the .last() method could have simplified retrieving the last row in this scenario:

it("Test case", function () {
    browser.get(browser.baseUrl);

    var button = element(by.xpath("//whatever"));
    var rows = element.all(by.xpath("//whatever"));

    button.click(); // adds a line

    expect(rows.last().getText()).toEqual("yay");
});

Alternatively, we can verify if the row count increases by one after clicking the button by using .then() to handle the promise from .count():

var button = element(by.xpath("//whatever"));
var rows = element.all(by.xpath("//whatever"));

rows.count().then(function (countBefore) {
    button.click();
    expect(rows.count()).toEqual(countBefore + 1);
});

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

Automate PDF Downloads using Python, Selenium, and Firefox

For instance: Using Selenium, I am trying to interact with the first Form 497. When I run this in my browser, a new tab opens showing the PDF. However, within the selenium code, nothing appears to be happening. This is the portion of my script, some sect ...

What is the name of the file that contains a class?

I am curious about identifying the file that called a specific class: database.ts class Database { constructor() { console.log(`I want to know who called this class`); } } server.ts import Database from 'database.ts'; new Databa ...

Why doesn't the error get translated into the model when I am utilizing ngModel.$setValidity?

Encountering an issue with nested directives and translating errors into the model. Check out the code sample here. .directive('myValidationDirective', [ function () { return { restrict: 'A', requir ...

Choosing Nested TypeScript Type Generics within an Array

I need help with extracting a specific subset of data from a GraphQL query response. type Maybe<T> = T | null ... export type DealFragmentFragment = { __typename: "Deal" } & Pick< Deal, "id" | "registeringStateEnum" | "status" | "offerS ...

Issue with Google map displaying incorrectly when attempting to print

I am experiencing an issue with printing a Google Map using the JavaScript API V3. The problem I am facing is that the map is split into two parts, with the top and bottom sections overlapping each other. Here is the code snippet: var geocoder; var ...

Different JavaScript entities with identical attributes (labels)

Even though JavaScript doesn't have tangible objects, I'm struggling to differentiate between them. Let's say we have two objects called Apple and Orange defined as follows: function Apple(){ this.name = "Apple"; } and function Orang ...

Failed jQuery AJAX request to database with no returned information

I'm really confused about where the issue lies :S The button triggers a function that passes the parameter "sex" and initiates an ajax call to ajax.php, where I execute a MySQL query to retrieve the results and populate different input boxes. When I ...

Content in React Router may fail to load when refreshing the page, navigating forward, or manually

I recently started using React and I'm getting familiar with React Router. I divided my application into two main routes because each uses a different style: the Splash path is for when the user first enters, which contains the Splash screen, Login, a ...

Basic HTML Audio Player Featuring Several Customizable Variables

I have a unique API that manages music playback. Instead of playing audio in the browser, it is done through a Discord bot. Achievement Goal https://i.stack.imgur.com/w3WUJ.png Parameters: current: indicates the current position of the track (e.g. 2:3 ...

How to enable Autocomplete popper to expand beyond the menu boundaries in Material UI

Within my Menu component, I have an Autocomplete element. When the Autocomplete is clicked, the dropdown list/Popper appears but it's confined within the Menu parent. How can I make it so that the Autocomplete's dropdown list/Popper isn't re ...

How to style the first dropdown value in AngularJS to appear bold?

Is there a way to style only the first value in a dropdown list as bold without using jQuery? Here is the code for the dropdown: <div class="col-xs-3"> <select-box id="ad-version-select" options="curItem.stats.version" model="state.version" i ...

Leverage the Power of Multiple Markers on Google Maps with API Integration

My project involves creating a WordPress site that displays one marker on a map and has a list of additional locations below it. I aim to remove the description under the map and replace it with a simple list of locations alongside markers on the map. ...

Utilizing Redux Reselect for Comment Filtering

Currently, I am attempting to filter and showcase comments that have a matching 'postID' with the current post id. Utilizing Redux/Reselect, the functionality works well but occasionally an error pops up indicating that post._id is undefined/null ...

Amplify encounters the "Failed to load resource: the server responded with a status of 400" issue

I encountered an error while using Amplify, although the build was completed successfully. Failed to load resource: the server responded with a status of 400 manifest.json:1 The system is functional in the local environment. Below is the Package.json scri ...

Steps for inserting a video into a new div upon selecting a hyperlink

Looking for a way to link menu elements to corresponding videos in adjacent divs? I have two divs set up - one with the menu list and another right next to it where the videos should be loaded. Forms seem like a potential solution, but I lack expertise i ...

How do I preserve data within $scope upon switching views using ng-include?

Can you please take a look at this jsFiddle? http://jsfiddle.net/mystikacid/b7hqcdfk/4/ This is the template code: <div ng-app="myApp"> <div ng-controller="dataCtrl"> <div>Data : {{data}} (Value outside views)</div> < ...

Travel to the root route of one BrowserRouter from a different BrowserRouter and encounter the message: "Warning: Maximum update depth exceeded."

When transitioning from one BrowserRouter to another BrowserRouter, the error message "Maximum update depth exceeded" is appearing. Caution: The maximum update depth has been surpassed. This issue can arise when a component calls setState within useEffec ...

What could be causing the issue of rows being undefined?

Need help creating a user registration feature with Passport(Local-Signup)? Check out the code snippet below: // config/passport.js // requiring necessary modules var LocalStrategy = require('passport-local').Strategy; // loading the user mode ...

Utilizing PHP configurations in JavaScript with AJAX for JSON implementation

Trying to have a config.inc.php file shared between PHP and JavaScript seems to work, but when using ajax, the "error-function" is always triggered. Is there a way to successfully share the config file with working ajax implementation? This is being utili ...

Issue at line 34: incompatible types error in Java - Cannot convert a String to WebDriver in Selenium

I am facing an issue with this error, and I can't seem to find any obvious mistake in the code. package driver; import io.github.bonigarcia.wdm.WebDriverManager; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; i ...