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
});