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

Error Encountered: AngularJS Form Email - SyntaxError: An unexpected token '<' was found in the code

My attempt to send an email from my AngularJS website involves the following setup: Contact.index.html: <form name="userForm" class="well form-search"> <input type="text" ng-model="name" class="input-medium search-query" placeholder="Name" ...

When the update button is clicked, the textfield is hidden; it reappears upon refreshing the page

Our marketplace multi-vendor site on Magento allows sellers to list their products for sale. The frontend displays the price using the following code: Phtml <input onFocus="showPriceCancel('<?php echo $products->getId(); ?>');" clas ...

Issue encountered while incorporating a PHP file into Javascript code

I'm facing a particular issue where I have a PHP file that is supposed to provide me with a JSON object for display in my HTML file. Everything seems to be working fine as I am receiving an output that resembles a JSON object. Here's the PHP file ...

What is the best way to incorporate multiple pages into a Node JS and Express application?

After completing a tutorial on Node JS for RPI (https://www.youtube.com/watch?v=QdHvS0D1zAI), I encountered an issue when trying to add multiple websites to my web app. While everything works fine locally on localhost:5000/page2, once I make the app public ...

Acquiring information to display in a div using innerHTML

I aim to create a div that displays different animal sounds, like: Dog says Bark Bark I've attempted various methods but I'm unable to get each pair in the array to show up in a div: const animal = [ {creature: "Dog", sound: "B ...

I am looking to manage the error handling service, and my next step is to intentionally insert a single error into my service and have it automated

Need help with error handling in my service. I want to manually insert a single error, but would like it to be done automatically instead. 'use strict'; angular.module('nexoolApp.errorservice', ['nexoolApp.config']) .servic ...

Vue 3 list fails to refresh

Using an API, we are retrieving data: <script setup> import { onMounted, inject } from 'vue' let list = []; function initializeData() { axios .post("/some-link/here") .then((response) => { list ...

Utilizing HighCharts' Reflow Feature for Dynamic Chart Resizing

Our Angular application utilizes highcarts-ng for implementing HighCharts. Check out the Chart Maximize and Minimize function that is currently operational: function expandChartPanel() { vm.chartMaxed = !vm.chartMaxed; viewHeader = ScopeFactory. ...

What is the best way to determine total revenue by consolidating data from various tables within an IndexedDB database?

Seeking guidance on building a stock/sales application in JavaScript with Dexie.js. I need assistance in efficiently calculating the Total Sales amount without resorting to overly complicated recursive code that triggers multiple queries for a single produ ...

Currency symbol display option "narrowSymbol" is not compatible with Next.Js 9.4.4 when using Intl.NumberFormat

I am currently utilizing Next.JS version 9.4.4 When attempting to implement the following code: new Intl.NumberFormat('en-GB', { style: 'currency', currency: currency, useGrouping: true, currencyDisplay: 'narrowSymbol'}); I ...

Preserving quotation marks when utilizing JSON parsing

Whenever I try to search for an answer to this question, I am unable to find any relevant results. So please excuse me if this has been asked before in a different way. I want to preserve all quotation marks in my JSON when converting from a string. In m ...

When using Selenium WebDriver, the test may freeze after waiting for the element to be clicked

My task involves clicking on a dynamically generated element using Selenium WebDriver (Java API). I have implemented WebDriverWait to wait for the element to appear and then perform the click operation. Surprisingly, the first click is successful, but when ...

Surprising outcomes when using Mongoose

Questioning Unusual Behavior There is a model in question: //test.js var mongoose = require('../utils/mongoose'); var schema1 = new mongoose.Schema({ name: String }) var schema2 = new mongoose.Schema({ objectsArray: [schema1] }); schema1.pre( ...

Timing issues with setInterval and setTimeout are causing them to execute at the incorrect moments

I am struggling with changing the background image using setInterval and setTimeout every x seconds. The issue I am facing is that the timer is not working as intended, causing images to change instantly instead. let images = ['background1.jpg&apo ...

The isEnabled() method unfailingly returns a value of true

My goal is to retrieve the list of Strings associated with enabled checkboxes. However, I am facing an issue where the isEnabled() method always returns true even for disabled checkboxes. Consequently, I end up getting a list of all the Strings present in ...

Headers can't be set after they have been sent. This issue arises when calling create(data,cb) function

I am a beginner in Node.js and I am attempting to create a model in MongoDB. However, when I make a call to localhost:3000/a, I notice that the request is being sent twice in the console and I am encountering an error stating "Can't set headers after ...

Best practices for sending variables to an HTML page using nodemailer

I am interested in sending an email with an HTML template that includes dynamic data. For example, I want to include a unique id within a link on the page. Is it possible to insert dynamic data into HTML content when sending emails? If yes, I would apprec ...

Encountering a problem with lazy loading of module routing paths. Issue arises when attempting to navigate to http://localhost:4200

AppLazyLoadingMoudle import {NgModule} from '@angular/core'; import {RouterModule, Routes} from '@angular/router'; const ROUTES : Routes = [ /* ProductModule (defined in the feature module) is loaded lazily when navigating ...

Issue with page scrolling while utilizing the Wow.js jQuery plugin

While using the Wow.js plugin for scroll animations, I encountered an issue on mobile phones. When reaching the Pricings section, scrolling becomes impossible for some reason. I am utilizing Bootstrap 3 in this project. Despite attempting to modify the an ...

Show a modal component from another component in Angular 2

As a newcomer to Angular, I'm working on a modal component that changes from hiding to showing when a button with (click) is clicked. The goal is to integrate this modal into my main component, allowing me to display the modal on top of the main conte ...