What are the steps to utilize PageObject in a dynamically created tab during a test execution?

When attempting to use my pageObjects in a newly opened tab during the test run, the test mistakenly interacts with the base page instead of the intended one. While working with a newly opened tab is successful when using const = [newPage], like in

newPage.locator('someLocator').click()
, I aim to streamline the test process by creating functions within the pageObject and reusing them with newPage.

Here is an example of my code:

pageObject:

export class SharedPage {
  /**
   * @param {import('@playwright/test').Page} page
   */

  constructor(page) {
    this.page = page;
    this.addToCartButton = page.locator('text=Add to cart');
  }
  async addToCartButtonClick() {
    await this.addToCartButton.click();
  }
}

Test:

import { test } from '@playwright/test';

import { LoginPage } from '../../pages/LoginPage';
import { ProductsPage } from '../../pages/ProductsPage';
import { SharedPage } from '../../pages/SharedPage';

const newPageLocators = {
  sauceLabsOnesie: 'text=Sauce Labs Onesie',
  sauceLabsBackpack: 'Sauce Labs Backpack',
};

test.beforeEach(async ({ page }) => {
  const loginPage = new LoginPage(page);
  await loginPage.goTo('inventory.html');
});

test('As a user I want to open a new tab and visit it', async ({
  page,
  context,
}) => {
  const productsPage = new ProductsPage(page);
  const [newPage] = await Promise.all([
    context.waitForEvent('page'),
    productsPage.openNewTabWithProduct(newPageLocators.sauceLabsBackpack),
  ]);
  const sharedPage = new SharedPage(newPage);
  productsPage.selectProductByText(newPage, newPageLocators.sauceLabsOnesie);
  newPage.locator(newPageLocators.sauceLabsOnesie).click(); // successfully interacts with the element
  sharedPage.addToCartButtonClick(); // unsuccessfully tries to interact with the base page
});

Answer №1

The main issue here is the absence of await before asynchronous Playwright API calls and also in your custom wrappers for them:

// ...
const sharedPage = new SharedPage(newPage);
await productsPage.selectProductByText(newPage, newPageLocators.sauceLabsOnesie);
await newPage.locator(newPageLocators.sauceLabsOnesie).click();
await sharedPage.addToCartButtonClick();
// ...

In your constructor, utilizing async/await is not feasible. Refer to Async/Await Class Constructor. Fortunately, Playwright enables you to combine locator().click() with a single await, so your class code appears fine for now, but it's important to keep this in mind as you expand your codebase.

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

Toggling forms with HTML <select> elements: A step-by-step guide

In the process of creating a web application, I am faced with the task of registering users based on their specific category. To accomplish this, I have incorporated a combo-box where users can indicate their user type. My objective is to display an appro ...

The Next.js page suddenly disappears after a moment

Out of the blue, my next.js page suddenly went blank for no apparent reason. I didn't make any changes, it just happened. I attempted to restart my dev server and even deleted the '.next' folder, but nothing seemed to fix the issue. Despite ...

How to locate the position of an element within a multi-dimensional array using TypeScript

My data structure is an array that looks like this: const myArray: number[][] = [[1,2,3],[4,5,6]] I am trying to find the index of a specific element within this multidimensional array. Typically with a 1D array, I would use [1,2,3].indexOf(1) which would ...

What is preventing me from using memoization in the getServerSideProps of NextJS?

I'm currently using React along with NextJS to showcase a variety of products on a specific category page. While I am able to successfully fetch the products utilizing getServerSideProps, I am not fond of how it continuously requests the product cata ...

The D3.js text element is failing to show the output of a function

I'm having an issue with my chart where the function is being displayed instead of the actual value. How can I make sure the return value of the function is displayed instead? The temperature values are showing up correctly. Additionally, the \n ...

Is it feasible to simultaneously load multiple directives in AngularJS?

I currently have a UI table with 5 columns, each containing different charts rendered using various directives such as custom progress bars and margin targets. The functionality is operating smoothly at the moment. Issue: When loading the page, it takes a ...

Learn the process of implementing multiple onClick listeners in React without deleting the existing ones

I'm facing a tricky situation with adding multiple event listeners based on different conditions. When the first condition is met, I attach a function to the click event: ref.current.onclick = ()=> {function1()} However, when the second condition ...

What is the best way to only buffer specific items from an observable source and emit the rest immediately?

In this scenario, I have a stream of numbers being emitted every second. My goal is to group these numbers into arrays for a duration of 4 seconds, except when the number emitted is divisible by 5, in which case I want it to be emitted immediately without ...

Just easy highlighting using tags in Javascript

I have come across a code snippet that seems to be functioning well: <html> <head> <title>Testing JS Highlighting</title> <script type="text/javascript"> function highlight() { var t = ...

Troubleshooting issue with JavaScript promise not functioning properly using resolve() method

I encountered an issue with promise usage in JavaScript. My objective was to retrieve data from firebase, store the results in an array, and then perform sorting on that array. Below is my code snippet: let promise = new Promise((resolve, reject) => ...

Encountering a problem with PDF view in Next.js while using html2canvas and jsp

Currently, I am using html2canvas and jspdf with Next.js to generate a PDF. However, the generated PDF does not display correctly. The h1 tag appears similar to the p tag, which is not the desired outcome. I need assistance in fixing this issue. My goal is ...

Effortless Basketball Movement Script in Javascript

What happens: Pressing the space button causes the ball to move up and then stop. When pressed again, it moves down. What I need: I want the ball to move up and then move down when I press the space button! I'm trying to figure out how to repeat thi ...

Obtaining data from JSON arrays

My current challenge involves extracting data from the following link: and storing it in my database. However, I am encountering difficulties with manipulating the array in order to retrieve the last unix datetime. Despite multiple attempts to extract th ...

What could be the reason for the Checkbox's value not showing up after making changes?

In my React and Material UI project, I am facing an issue where I want to check all checkboxes in a list by simply checking one checkbox in a parent component. Despite passing down the correct value of the parent checkbox through props, the visual changes ...

Guidelines for sending JSON Data via Request Body using jQuery

I'm not well-versed in jQuery, so consider me a beginner. Here's my code that is not correctly handling JSON data submission via Request Body. <!doctype html> <html lang="en> <head> <title>jQuery JSON Data Submission ...

Validation of user input using jQuery

Trying to ensure that the form inputs are not empty has been a challenge. Despite using jQuery for input validation, it seems that the inputs are not being properly checked. Strangely, the submit button still allows the form to be submitted: <form id=" ...

I'm having trouble figuring out why this React Router setup is not functioning properly. Can anyone provide any insights

As I delve into react routing practice, I've put together a geography-based web app. Starting off, I configured the router paths: import { StrictMode } from "react"; import { createRoot } from "react-dom/client"; import { BrowserRo ...

Choose the grandparent of an element's parent

Is there a way to select the grandparent element of a child in Javascript without having to chain the .parentElement method twice? Specifically, I am looking for a method that can substitute .parentElement.parentElement when selecting the desired element, ...

What is the best way to trigger a mouseup event in Vue when the mouse is released outside of a specific element?

To capture the mousedown event on the element, you can simply add @mousedown. If the cursor is lifted inside the element, using @mouseup will capture the event. However, if the mouse goes up outside of the element (even outside of the browser window), the ...

Inkwell shifts bespoke quality

I am currently utilizing Quill (v.2.0.0) with quill-better-table (v.1.2.10) within my Angular 13 project. I am attempting to incorporate a custom attribute to the table tag, as shown below: <table class="quill-better-table" custom-attribute=& ...