Protractor's count() function fails to execute properly when called outside of a promise loop

var alerts = element.all(by.xpath("//div[@class='notification-content']"));
alerts.count().then(function (val) {
    console.log(val);
});
 let compareValue = val;

Is there a way to access the 'value' outside of the promise loop for comparison with another variable? I want to compare this 'value' without using an exception statement. Any guidance would be appreciated.

Answer №1

Here's a great example showcasing asynchronous programming in JavaScript. To delve deeper into this topic, check out Protractor: Exploring the variance between ignoreSynchronization and async/await in Protractor. This will provide clarity on how the execution process unfolds.

To address your query, consider implementing async/await instead of .then to capture and save the value.

it('should retrieve count', async () => {
  await browser.get("application URL");
  let count = await element.all(by.xpath("//div[@class='notification-content']")).count();
  console.log(count);
});

Hoping this resolves your question.

Edit:

it("test", () => {
    let count1, count2;
    browser.get("application URL");
    var notifications = element.all(by.xpath("//div[@class='notification-content']"));
    count1 = notifications.count();
    var notifications = element.all(by.xpath("//div[@class='notification-content']"));
    count2 = notifications.count();
    expect(count1).toBe(count2);
  });

Answer №2

In this situation, it is recommended to utilize async/await for better performance. However, if you must proceed with the method provided in your snippet, the implementation would look like this:

var notifications1 = element.all(by.xpath("//div[@class='notification-content1']"));
var notifications2 = element.all(by.xpath("//div[@class='notification-content2']"));

notifications1.count().then(function (count1) {
  notifications2.count().then(function (count2) {
    expect(count1).toEqual(count2);
  }
});

Answer №3

Give it a try!

Instead of using promise chaining, consider implementing async/await. Promise chaining can be complex and may not offer the same flexibility when writing code. Check out this link for more information on async/await.

let notifications;
let value;

async function GetElementCount() {
   notifications = await element.all(by.xpath('//div[@class=\'notification-content\']'));
   return notifications.count();
}

value = await GetElementCount();

You can now print the 'value' variable outside and compare it with another variable.

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

Energetic flair for Vue animations

I am currently developing a VueJS sidebar component. The objective is to allow the parent to define a width and display a toggle button that smoothly slides the sidebar in and out. Here is an example: <template> <div class="sidebarContainer ...

Unable to retrieve information from the firestore database

When trying to fetch documents from the firestore, I encountered an issue where it returns an empty array. However, when I run console.log(docs); outside of the declared function, it actually shows the array data. This problem arises because my useEffect f ...

Uncovering the Android tablet browser: A guide

I have implemented the code below to detect mobile/tablet browsers. function isMobile() { var index = navigator.appVersion.indexOf("Mobile"); return (index > -1); } Although it works well for desktop browsers and iOS devices (iPhon ...

The client using socket.io is receiving events for "double plus one"

While experimenting with socketio, I encountered a bug that others are experiencing as well but I haven't been able to find a valid solution. This is the server-side code: const app = require('express')(); const server = require('http& ...

What is the best way to simulate global variables that are declared in a separate file?

dataConfiguration.js var userData = { URIs: { APIURI: "C" }, EncryptedToken: "D" }; configSetup.js config.set({ basePath: '', files:['dataConfiguration.js' ], ..... UserComponentDetails: .....some i ...

Sort array of objects alphabetically and move objects with value to the beginning

I have a dataset that consists of different arrays of objects. When I log myData, the output looks something like this: [ { name: 'Cdb', image: 'xxx', coll: 'xxx' }, { name: 'Bcd', image: &a ...

standard_duration for Junior Selenium experiments

Is there an equivalent to Capybara's (RoR) default_wait_time for the Intern? setPageLoadTimeout and setFindTimeout don't seem to accomplish anything. this.timeout = 60000 seems to give an entire test 60 seconds, but I want all steps to have a d ...

Is it possible to encase <v-img> within an anchor element?

I am currently using Vuetify 1.5 and have included a couple of <v-avatars></v-avatars> elements in which there is a nested <v-img></v-img>. I attempted to enclose the img tags within an a tag but encountered an issue wherein the ima ...

Deactivate a <tr> element if any of its <td> cells contain a value

In my table, there are various trs and tds with different element names. I need to determine if there is text in a specific field. If there is text, I want to disable or hide the entire tr to prevent user interaction. Unfortunately, I am unable to provide ...

Is it possible for you to pinpoint the mistake in the code below?

I've been trying to locate an error in the function but have been unable to do so. As a beginner in this area, I would appreciate your patience. <html> <head><title>print names</title> <script langua ...

Position a BoxGeometry in a straight line between two points in 3D space

In my game, I have the ability for players to add objects to a world without being restricted to a grid. Now, I am working on adding footpaths to the game. When the player clicks on "Create footpath", they can add a point in the world at the location of th ...

Tips for consuming a REST API to retrieve JSON data and assign it to a variable for use in React JS

I'm currently working on developing a shopping application using React.js. I found inspiration from a sample application on https://codepen.io/paulkim/pen/oZLavq , and now I am looking to fetch product information from an API call. I have attempted to ...

I'm experiencing an issue with Bootstrap 5 where the code runs fine on codeply but not on my local machine

I'm attempting to replicate the scrollspy example found on the Bootstrap website. You can see my attempt here: . Feel free to inspect the code. While the navigation links function correctly, I've noticed that according to Bootstrap's docum ...

Issue with event binding on datepicker that is dynamically added is not functional

I have integrated the Kendo datepicker into my project, and I am facing an issue with duplicated div elements containing datepickers. The problem is that the datepicker events only fire once on the first duplicated div and then stop working altogether. I ...

How to fetch files using URL in JavaScript

I need a solution for automatically downloading multiple PDF files from Google Drive and Docs using their URLs with JavaScript code. I don't want to manually go to each link to download the files. Although I've researched various answers on Stac ...

Issue with the Ajax auto-complete feature in Internet Explorer

I am facing an issue with my "ajax suggestion list" getting hidden behind the "select menu" located right below the text box that triggers the ajax function. This problem only occurs in IE 6.0, while it works fine in other browsers. I have already disabled ...

Managing multiple sets of radio buttons using the useState hook

Within my renderUpgrades-function, I handle the options of an item by including them in radio-button-groups. Each item has multiple options and each option has its own radio-button-group. Typically, a radio-button-group can be managed using useState, wit ...

Is combining form and fieldset causing issues?

My <form> for uploading an image and my <fieldset> for sending data via AJAX both work individually. However, when I try to merge them into one form, things get complicated. This is being done on a Node.JS server. Upload <form>: <for ...

Is there a way for redux-saga to pause until both actions occur at least once, regardless of the order in which they happen?

Just diving into Redux saga. I'm working on creating a saga that will fetch the initial state for the redux store from our API server. This task involves utilizing two asynchronous sagas: getCurrentUser and getGroups. The goal is to send these ajax ...

The error message "Invalid Data Type: Not an Array - google charts" was encountered

I am struggling with an ajax call that I have set up. The issue arises when passing an array from the backend to the frontend. Upon checking the data through an alert on the frontend, everything seems fine. However, Google charts raises an error stating th ...