I implemented a Page Object Design pattern to my automation suite and for a simple test case, I’m trying to get total number for elements from a simple table in https://www.saucedemo.com/inventory.html website. But unfortunately im getting
Error: locator.waitFor: Target closed
=========================== logs ===========================
waiting for locator('xpath=//div[@class="inventory_item"]') to be visible
============================================================
at ../pages/InventoryPage.ts:19
17 |
18 | async selectRandomItem(){
> 19 | await this.colTable.waitFor({state: "visible"}); //issue is here
| ^
20 | const itemCount = await this.colTable.count();
21 | return await itemCount;
22 | }
This is my inventory.spec.ts file
import { test, expect } from '@playwright/test';
import { LoginPage } from '../pages/LoginPage';
import { InventoryPage } from '../pages/InventoryPage';
test.describe("Inventory Page Tests", () => {
let loginPage: LoginPage;
let inventoryPage: InventoryPage;
test.beforeEach(({ page }) => {
loginPage = new LoginPage(page);
inventoryPage = new InventoryPage(page);
});
test("TC-003: Checking whether random item can be addded to the cart", async ({ page }) => {
await test.step("1.Log in to the site", async () => {
await loginPage.visit();
});
await test.step("2.Enter correct username and password", async () => {
await loginPage.login("standard_user", "secret_sauce");
});
await test.step("3.Get the number of elements", async () => {
await console.log(inventoryPage.selectRandomItem());
});
});
});
This is my InventoryPage.ts file
import { Locator, Page } from "@playwright/test";
export class InventoryPage {
readonly page: Page;
readonly lblLoggedIn: Locator;
readonly colTable: Locator;
constructor(page: Page){
this.page = page;
this.lblLoggedIn = page.getByText('Products');
this.colTable = page.locator('//div[@class="inventory_item"]'); //This is the common element
}
async selectRandomItem(){
await this.colTable.waitFor({state: "visible"}); //issue is here
const itemCount = await this.colTable.count();
return await itemCount;
}
}
How to fix this issue? This is the table im trying to get total elements
2
Answers
waitFor() can be used only on a locator that returns a single element, and as you are trying to apply to it a locator that returns multiple elements, it will throw an error.
You will have to wait for some other element/event.
You need to
await
an async function prior to console.log