Hi All,
I'm using saucedemo.com and playwright + typescript. All I'm trying to do is log in, then add all the items to the cart.
Here's my code:
const products = await page.getByRole('button').filter({ hasText: 'Add to cart' }).all(); products.forEach(async (addToCart) => { await expect(addToCart).toBeVisible({timeout: 10000}); await addToCart.click(); });
There's 6 products on the products page, each one has an add to cart button, so I found all the buttons and put them in a list, then iterate on that list to click the button.
I'm getting the error mentioned in the title. The trace file is attached. Really stumped on this one, any help is appreciated!
This thread is trying to answer question "Why does the error 'locator.click: Target closed' occur when using a forEach loop with async/await in playwright and typescript on saucedemo.com, and how can it be resolved?"
Ah makes sense, coming from python and c#, trying to force a forEach when it's not necessary. for... x of y is great to know.
Unfortunately, I'm still having an issue...
There are 6 buttons total, but only the first 3 buttons are being successfully clicked. The rest are not able to be found. I'm wondering if because the button text is changing once clicked, that the original locator I used is no longer valid?
await page.goto('https://www.saucedemo.com/');
await page.locator('[data-test="username"]').fill('standard_user');
await page.locator('[data-test="password"]').fill('secret_sauce');
await page.locator('[data-test="login-button"]').click();
const productsLocator = page
.getByRole('button')
.filter({ hasText: 'Add to cart' });
await expect(productsLocator).toHaveCount(6);
let products = await productsLocator.all();
while (products.length > 0) {
await expect(products[0]).toBeVisible();
await products[0].click();
products = await productsLocator.all();
}
Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email [email protected].