microsoft / playwright

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.
https://playwright.dev
Apache License 2.0
67.13k stars 3.69k forks source link

[Feature]: An option to click a locator from a list randomly. #31051

Closed ColeGebhard closed 5 months ago

ColeGebhard commented 5 months ago

🚀 Feature Request

Similar to .last(), and .first() methods. Possibly a .random() or a way to specify which index to choose from a list of locators.

Example

I understand I could possibly use a evaluateAll method, but to have this would be beneficial to tests in say an ecommerce store. For tests that include having multiple items in a cart, and updating randomly instead of just using first/last.

const quantityChange = await page.getByRole("button", { name: "Plus" });
const numberOfOptions = await page.getByRole("button", { name: "Plus" }).count();
const randomIndex = Math.floor(Math.random() * numberOfOptions);

await quantityChange[randomIndex].click();

Which sees quantityChange[randomIndex] as undefined. Having a .random would be beneficial in this scenario. More specific locators would be difficult to implement due to the variety of items being added.

Motivation

This would not only improve a specific portion of tests but for any possibility of not needing to rely on a specific locator to be available for a .click() method for example.

With .first() and .last() being methods already, it shows a reliance of not needing a more specific locator, and a new method like .random() would fit in nicely with the two.

dgozman commented 5 months ago

@ColeGebhard .random() goes against one of the most important properties of a test - reproducibility. We love it when a test is 100% reproducible, so that you can see what went wrong, re-run it on your computer and fix the problem.

If you need something along these lines, I'd recommend using locator.nth() instead and choose the index as you like it. I'd go with .nth(0), .nth(1) and .nth(2) for reproducibility, but you can do something else. Let me know whether this helps.

dgozman commented 5 months ago

Closing as per above. If you still encounter problems, please file a new issue.

ColeGebhard commented 5 months ago

I definitly understand, thank you for that .nth(value) action!