Determine the number of web elements on a page using Protractor

What is the best way to get the count of elements on a page? Here is my code snippet:

public countElements(){
    element.all(by.repeater('app in userApps')).count().then(function(count) {
        console.log(count);
      });
      return count; // unable to retrieve element count
}

I understand that the count is invisible outside the function, but how can I make it visible? How can I properly return the count variable in the method countElements() ?

Answer №1

function getTotalElements(){
    return elements.all(by.repeater('item in items')).count();
}

Next, in the testing phase:

page.getTotalElements().then(total => {
    console.log(total);

    expect(total).toBe(expectedTotal);
});

If you want to use the total count in other functions, consider using async/await.

let total = await page.getTotalElements();
anotherFunction(total);

Alternatively, you can create your custom promise and resolve it. You can achieve this by implementing something similar to the following code.

function getTotalElements(){
    return new Promise((resolve, reject) => {
        elements.all(by.repeater('item in items'))
          .count()
          .then(total => {
              if(total > 0) {
                resolve(total);
              } else {
                reject('An error occurred...');
              }
          });
    }        
}

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

The specified control name formControlName in the Angular reactive form cannot be located

Having encountered this issue multiple times on Stack Overflow without any success, I am reaching out for help to identify what I might be doing wrong. In my component : ngOnInit() { this.companyCreatForm = this._formBuilder.group({ name: [null, ...

Confusing Error and Misunderstanding Related to Generic Function Subtyping Constraints

I had an idea to create a simple wrapper function using TypeScript. After some trial and error, I was able to make it work with the following code: export function logFn<T extends (...args: any[]) => any>( fn: T, ): (...args: Parameters<T> ...

Encountering persistent download pop-up boxes in Python 2.7 with Selenium 3.8 on Firefox 57 and MacOS Sierra, despite setting "browser.helperApps.neverAsk.openFile"

Struggling with downloading PDF files from a webpage using Selenium 3.8, Firefox 57, and Python 2.7. Without manually changing the Firefox profile settings to specify a download location, the download pop-up box keeps appearing and the files don't dow ...

The interpolated string type is not allowed to be utilized for indexing a record that has the identical type as the key

I'm attempting to utilize an interpolated string form to access a Record type using a key that should match the record's key type. Unfortunately, it doesn't appear to be functioning as expected. Here is a simple example: type TypeOfKey = `c ...

Unleash the potential of a never-ending expansion for grid cells on Canvas

ts: templateStyle = { display: 'grid', 'grid-template-columns': 'calc(25%-10px) calc(25%-10px) calc(25%-10px) calc(25%-10px)', 'grid-template-rows': '150px auto auto', 'grid-gap ...

When combining Webassets with Typescript, encountering issues resolving symbols or modules

I've organized my Flask project with the following structure: ├─ app.py ├─ project | ├─ __init__.py | └─ static | └─ typescript | └─ app.ts └─ typings ├─ globals | └─ ... # multiple imported ts ...

A guide on dynamically showcasing/summoning icons in react by utilizing array data

QUESTION: 1 (SOLVED!) https://i.stack.imgur.com/1M1K7.png What is the best way to display icons based on an array of data codes? const data = [{ img: '01d' }, { img: '02d' }] if(data) { data.map((item) => ( <img src={`./ ...

Tips for maintaining knowledge after redirecting to a new page

Building an app using Ionic 4 where I need to display vouchers from a database as images. Each image should act as a link to a details page showing more information about that specific voucher. However, I am struggling to figure out how to keep track of th ...

Issues encountered while establishing a connection to an API in React Native

When attempting to log in a user by connecting to my API, I encountered some issues. It seems that every time my laptop has a different IP address, I need to make changes in the file where the fetch or XMLHttpRequest is located in order for the login proce ...

VSC is throwing a type error, but is it still possible to compile the code?

It seems like after downloading some extensions, I started encountering this issue which was not present before. My files are now displaying errors even though everything should be fine. https://i.sstatic.net/cr7Ef.png The error seems to be related to ca ...

Using React Native to dynamically change color based on API response

I'm currently working on a React Native project and I have a requirement to dynamically change the background color of a styled component based on the value retrieved from an API. However, I'm facing some challenges in implementing this feature. ...

What methods are available to restrict the values of properties to specific keys within the current type?

I am looking to declare an interface in typescript that is extensible through an indexer, allowing for the dynamic association of additional functions. However, I also want sub properties within this interface that can refer back to those indexed functio ...

Consolidate all REST service requests and match the server's response to my specific object model

My goal was to develop a versatile REST service that could be utilized across all my services. For instance, for handling POST requests, the following code snippet demonstrates how I implemented it: post<T>(relativeUrl: string, body?: any, params?: ...

Determine data type using the generic type of a related property in Typescript

I am seeking a method to specify the type of a property based on the generic type of another property within the same context. For instance, consider the following: type Person = { id: number; name: string; } type Select<Value=unknown> = (props ...

A guide to removing duplicate values from dropdown menus filled with API data in a React application

I am encountering an issue with my three dropdowns - Manufacturer, Province, and City - as they are fetching data from an API but displaying duplicate values instead of unique ones. Context: The API stores information for approximately 50 products. There ...

Refresh the project once logged in using angular

Thank you in advance for your response. I am facing an issue with monitoring user activity and automatically logging them out after a certain period of inactivity. I have successfully implemented this feature in my app.component.ts file, however, it only s ...

Understanding the limitations of function overloading in Typescript

Many inquiries revolve around the workings of function overloading in Typescript, such as this discussion on Stack Overflow. However, one question that seems to be missing is 'why does it operate in this particular manner?' The current implementa ...

The React.FC component encountered an invalid hook call

I've encountered an issue while using TypeScript and trying to implement a hook within React.FC. Surprisingly, I received an error message stating that hooks can only be used inside functional components. But isn't React.FC considered a functiona ...

Can a custom structural directive be utilized under certain circumstances within Angular?

Presently, I am working with a unique custom structural directive that looks like this: <div *someDirective>. This specific directive displays a div only when certain conditions are met. However, I am faced with the challenge of implementing condit ...

Error thrown due to syntax issues in react.d.ts declaration file in TypeScript

Currently, I am attempting to integrate react with typescript in my project. However, typescript is generating syntax errors for the react.d.ts file sourced from Github: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/react The encountered ...