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 files to make it easier to explain the problem, but it seems to revolve around instantiating the new page object. I'm not sure how to handle this better. Can anyone guide me in the right direction?

basePageObject.ts

import { browser, by, element, ExpectedConditions } from 'protractor';
import {NextPageObject} from './nextPageObject';

export class BasePage {

async navigateTo() {
 await browser.get('http://localhost:8080');
}

async launchThing() {
 await element(by.css('#launchThing')).click();
}

async clickNavToNextPage(): Promise<NextPageObject> {
 await element(by.css('#nextPageNav')).click();
 return new NextPageObject();
}
}

nextPageObject.ts

import { browser, by, element, ExpectedConditions } from 'protractor';

export class NextPageObject {

private firstNameField = element(by.css('.testFirstName'));

async getFirstName(): Promise<string> {
 return await this.firstNameField.getAttribute("value");
}

async enterFirstName(firstName: string): Promise<NextPageObject> {
 await this.firstNameField.clear();
 await this.firstNameField.sendKeys(firstName);
}

}

testSpec.ts

import { browser, by, element } from 'protractor';
import { BasePage } from 'basePageObject';

const expectedName = "Peter";

fdescribe('Navigation with custom URL', function() {
let page: BasePage;

beforeEach(async () => {
 page = new BasePage();
 await page.navigateTo();
});

fit('page nav', async function() {
 await page.navigateTo(url);

 const next1 = await page.clickNavToNextPage();
 expect(element(by.css('body > next-page- 
 header')).isPresent()).toBe(true);

 await next1.enterFirstName("Peter");

 // this fails as an empty string is returned but is close to the way 
 //I want to do things
 const firstNameFieldValue = await next1.getFirstName();
 expect(await firstNameFieldValue).toEqual(expectedName);

 // this works but is not how I want to do it
 const elementval = element(by.css('.testFirstName'));
 expect(elementval.getAttribute('value')).toEqual(expectedName);

}
}

Answer №1

Consider making a modification to the following line:

private firstNameField = element(by.css('.testFirstName'));

Change it to:

private get firstNameField() { return element(by.css('.testFirstName')); }

The difference between the two versions is that in the initial version, element() is called before sending the keys, while in the revised version, it is executed after sending the keys.

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

Each property of an object has its own unique key, yet they all share the same data type

I have a single-use object with only three properties, all of which should be of the same type. The code below currently achieves this, but I'm curious if there is a more efficient way to declare the type for timingsObject: let timingsObject: ...

Is it considered poor coding practice to utilize the store.dispatch method within an effect in an Angular NgRx application?

This particular question is an extension of a post that can be found here. However, I believe my query is more focused and specific, so I feel it's worth pursuing an independent answer rather than relying solely on the linked post. Context In the af ...

typescript - specifying the default value for a new class instance

Is there a way to set default values for properties in TypeScript? For example, let's say we have the following class: class Person { name: string age: number constructor(name, age){ this.name = name this.age = age } } We want to ens ...

Is there a way to close the MatBottomSheet by going back in the browser?

I'm currently utilizing https://material.angular.io/components/bottom-sheet/overview. I've encountered an issue where, when the bottom sheet is open and a user clicks on the back button in their browser, they are redirected away from the page tha ...

Determine the return type of a function based on a key parameter in an interface

Here is an example of a specific interface: interface Elements { divContainer: HTMLDivElement; inputUpload: HTMLInputElement; } My goal is to create a function that can retrieve elements based on their names: getElement(name: keyof Elements): Elemen ...

Combining data types to create a unified set of keys found within a complex nested structure

This problem is really testing my patience. No matter what I do, I just can't seem to make it work properly. Here's the closest I've come so far: // Defining a complex type type O = Record<'a', Record<'b' | 'x& ...

Tips for effectively utilizing Mongoose models within Next.js

Currently, I am in the process of developing a Next.js application using TypeScript and MongoDB/Mongoose. Lately, I encountered an issue related to Mongoose models where they were attempting to overwrite the Model every time it was utilized. Here is the c ...

Create collaborative documents with serverless TypeScript extension

Utilizing Amazon Lambda AWS along with Serverless and the Serverless Plugin TypeScript to develop my TypeScript files has been quite a challenge. I have implemented shared code in my project, organized within folders such as: /shared: shared1.ts, shared2. ...

Can an @Input value be transmitted to the app.component in Angular 2?

As I work on my Angular 2 app using ASP.Net for rendering, I find myself facing a challenge when trying to pass initialization data from RAZOR into my bootstrapped component. Despite setting up the _Layout.cshtml as the only RAZOR page, the data transfer d ...

Creating a comprehensive object within a single interface using Typescript

Here is an example of an Object in TypeScript: export class test{ recordname: string; comments: [{ comment: string }] } To define it using one interface instead of multiple interfaces, you can try something like this: export int ...

Having trouble resolving npm install -g @angular/cli due to issue with checking the installable status of [email protected] module

When attempting to install @angular/cli using the npm command in the command prompt, I encountered an issue with resolveWithNewModule. It seems to be stuck at checking installable status.[email protected] ...

Learn the art of bypassing TypeScript errors using @ts-ignore!

I recently encountered an issue when trying to import a pure JavaScript library into a TypeScript project, resulting in the error message: Could not find a declaration file for module xxx. After some research, I learned that this error can be suppressed u ...

How can you store form field validation rules (for example, firstname.dirty) in an array within TypeScript in Angular?

How do I save form field validation rules in an array? What should replace /'''''HERE'''''/ with? formfields: Array<Object> = [ {label: "Employer:", control: "employer", val ...

Having trouble with installing the angular-4-data-table-bootstrap-4 package in NG 4.4.6 environment

I am currently working on an NG 4 project and my package.json indicates that I am using angular 4.4.6. I am attempting to include the angular-4-data-table-bootstrap-4 package as outlined below, but I keep encountering the error mentioned here that I can&ap ...

Refreshing manually will display only the JSON data

Utilizing a NodeJS server to fetch information from a MySQL database and presenting it as a JSON object is the task at hand. app.get('/random', (req, res) => { var connection = mysql.createConnection({ host: 'localhost', ...

The Ionic search bar will only initiate a search once the keyboard is no longer in view

In my Ionic application, I have implemented a search bar to filter and search through a list. The filtering process is triggered as soon as I start typing in the search bar. However, the updated results are not displayed on the screen until I manually hide ...

Sending a POST request that is attempting to insert empty values into an MS SQL database

Here is the code I am working with - onSubmit(){ var headers = new Headers(); headers.append('Content-Type', 'application/x-www-form-urlencoded'); let postParams = { firstName : this.firstName, lastName : this.lastNa ...

The combination of mat-icon-button and mat-raised-button is not rendering properly in Angular Material 15

After upgrading to Angular v15 + Angular Material v15, the previous code that used Angular v14 + Angular Material v14 looked like this: The code for the icon button is shown below: <button *ngIf="admin" class="edit-btn" ...

Updating DynamoDB objects seamlessly in Lambda functions without any conflicts

I am currently working with example Objects that follow this interface structure: interface Car{ id: Number; name: String; tires: Wheel[] } interface Wheel{ id: Number; name: String; radius: Number; } My goal is to store these Car Objects in DynamoDB and ...

Angular reloads content when language is switched

I am facing an issue with my language selector and default pipes for number or currency format. Even after changing the language (e.g., from en-US to fr-FR), the thousands separator remains unchanged despite the correct updates in LOCALE_ID and TranslateSe ...