Protractor's Page Object returning inaccurate count

I am currently working on writing e2e tests for an Ionic app using Protractor and Cucumber. I have implemented a page object pattern, but I am facing an issue where the call to count() is returning 0, even though I have waited for the elements to be present. Strangely, adding a sleep function makes it work. Here's a snippet of my step definition:

Then('my cases should be listed', function (callback) {
  casesPage.isLoaded()
  .then(() => {
    expect(casesPage.numberOfFamilies())
      .to.eventually.equal(20)
      .and.notify(callback);
  })
});

This is my page object code:

import { browser, $, $$, by, ElementFinder, ElementArrayFinder } from 'protractor';

export class CasesPage {

  listOfFamilies: ElementArrayFinder;

  private initializePromise: Promise<void>;

  async initialize(): Promise<void> {
    if(!this.initializePromise) {
      return this.initializePromise = new Promise<void>(async (resolve) => {
        this.listOfFamilies = $$('ul.families li.family');
        return resolve();
      });
    }
  }

  get() {
    return browser.get('/cases')
  }

  async isLoaded(): Promise<boolean> {
    await this.initialize();
    return this.listOfFamilies.isPresent();
  }

  async numberOfFamilies(): Promise<number> {
    await this.initialize();
    // browser.sleep(3000); Uncommenting this works
    return this.listOfFamilies.count();
  }

}

Any suggestions on how to fix this issue?

Answer №1

An error arises when calling this.listOfFamilies.count() because it returns a Promise that needs to be resolved. Simply insert the await keyword before it:

  async getNumberOfFamilies(): Promise<number> {
    await this.initiate();
    return await this.listOfFamilies.count();
  }

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 promise briefly returns a placeholder object before resolving with the actual response

Currently, I am working on a simple check to determine whether myAnswer contains an answer. The checking functionality is operating smoothly; however, the issue arises in the final function that aims to return the string obtained from myAnswer. Instead of ...

Customize the height of individual carousel items in Primeng carousel

Hey there, I'm currently using the primeng carousel component and running into an issue where the carousel height is always based on the tallest item. I am looking to have an automatic height for each individual carousel item instead. Do you think th ...

How can you incorporate a module for typings without including it in the final webpack bundle?

As I venture into the realm of Webpack, I am faced with the challenge of transitioning from TypeScript 1.x to TypeScript 2. In my previous projects, I typically worked with TypeScript in one module using separate files, TSD for typings, and compiling throu ...

"Storing a collection of PDF files in an array in TypeScript Angular - A step-by-step

Here we have an HTML code snippet that includes an input file element with Angular: <input type="file" class="btn btn-info" id="archivoPDF" #PDFfile value="Seleccionar PDF(s)" accept="application/pdf" multiple /> And this is the TypeScript code sni ...

Escaping the confines of a Protractor loop using .filter() or .map()

Currently utilizing the Protractor and cucumber framework, I am encountering a challenge with breaking out of a .filter or .map loop. My goal is to discontinue iteration once a match is found! Page.prototype.getElementByKey = function (key) { var fo ...

Exploring the use of TypeScript and Webpack to read non-JavaScript files in Node.js

I'm working on a backend NodeJS setup written in TypeScript that is using webpack for compilation. However, I encountered an error when trying to read a text file even though I confirmed that the file source/test.txt is being copied to the build fold ...

Tips for type guarding in TypeScript when using instanceof, which only works with classes

Looking for a way to type guard with TypeScript types without using instanceof: type Letter = 'A' | 'B'; const isLetter = (c: any): c is Letter => c instanceof Letter; // Error: 'Letter' only refers to a type, but is being ...

Upgrade from Angular 4 to Angular 5 via the Visual Studio template is causing some challenges

I am in the process of upgrading my Angular project from version 4 to version 5, which is included in the template provided by Visual Studio 2017 (File -> New -> Project -> ASP.NET Core Web Application -> Angular). However, all the angular pac ...

Encountering errors with ng build --prod in Angular 2, but no issues when running ng serve

After attempting to deploy my Angular 2 app to Heroku, I encountered a daunting list of errors when trying to build for production. Interestingly, the app runs smoothly without any issues or errors when using 'ng serve'. You can view the full li ...

The 'connectedCallback' property is not found in the 'HTMLElement' type

After taking a break from my project for a year, I came back to find that certain code which used to work is now causing issues: interface HTMLElement { attributeChangedCallback(attributeName: string, oldValue: string, newValue: string): void; con ...

Endlessly streaming data is requested through HTTP GET requests

I am facing an issue with my code where it requests data endlessly. The service I have retrieves data in the form of an Array of Objects. My intention is to handle all the HTTP requests, mapping, and subscriptions within the service itself. This is because ...

Passing parent form controls from an Angular 4 FormGroup to a child component

I have implemented Angular Reactive Forms FormGroup and FormArray in my project. The issue I am facing is related to splitting my form fields into child components and passing the parent form controls to them. I expected this to be a straightforward proces ...

What is the best way to organize checkboxes (either checked or unchecked) within a mat-table?

https://i.stack.imgur.com/cDQY7.png <ng-container matColumnDef="scheduled"> <th mat-header-cell mat-sort-header *matHeaderCellDef> Scheduled </th> <td mat-cell *matCellDef="let station"> ...

What is the best way to combine various ngrx selectors together?

I currently have 3 selectors in my index.ts file export const selectDetails = createSelector( // some code ); export const selectTransactionResponse = createSelector( // some code ); export const selectAdditionalDetails = createSelector( // some code ); ...

Utilizing ternary operators in Angular 6 tables

I need to dynamically display certain amounts based on the comparison of two interest values. Here is the logic: <td *ngIf="subTable.flexitaxMaxPaymentDate"> subTable.flexitaxMaxInterest > subTable.IRDInterest ? {{subTable.maxAmou ...

What is the most effective way to extract necessary data and attributes from XML code?

Working with angular, I am receiving an XML response from a call to my API. Specifically, I need to extract the name attribute of the bpmn:task property from the XML. <bpmn:process> <bpmn:task Id= "Loopin809" name="Process 1" > <bpmn:Incom ...

Accessing Next and Previous Elements Dynamically in TypeScript from a Dictionary or Array

I am new to Angular and currently working on an Angular 5 application. I have a task that involves retrieving the next or previous item from a dictionary (model) for navigation purposes. After researching several articles, I have devised the following solu ...

Exploring the correct navigation of page objects through Protractor using TypeScript

I'm working on setting up a protractor test suite with TypeScript and running into an issue involving chaining of pageObjects for multiple pages. I haven't seen any examples that deal with this specific scenario. I've simplified the example ...

Typescript's intriguing concept of objects containing arrays inside other objects

I have a structure similar to this and I am trying to create definitions for types/interfaces, but I am facing issues in making it work correctly. layoutsSet: { 1: { "lg": [ { i: "1", x: 0, ...

Break down and extract elements using typedEvent in TypeScript

Within the external library, there is the following structure: export interface Event extends Log { args?: Result; } export interface TypedEvent<EventArgs extends Result> extends Event { args: EventArgs; } export type InstallationPreparedEven ...