What is the reason for the `all()` function of a locator in @playwright/test returning an empty list even when it resolves to multiple elements?


Understanding the all() Function in @playwright/test

The all() function of a locator in @playwright/test doesn't wait for elements to match the locator. It immediately returns whatever is present on the page at that moment. If your page's elements change dynamically, calling locator.all() can produce unpredictable results.

Here's how you can ensure accurate results:

Wait for Elements to Load

Before calling locator.all(), make sure all elements have finished loading. You can use Playwright's waiting mechanisms, like waiting for a specific condition or event.

await page.waitForSelector('.my-element');
const elements = locator.all();

Interact with Returned Elements

The all() function returns an array of locators pointing to respective elements. You can interact with each element using Playwright's methods.

const elements = locator.all();
elements.forEach(async (element) => {
  await element.click();

In conclusion, if locator.all() returns an empty list when you expect multiple elements, it's likely due to dynamic changes in the elements. Always wait for all elements to load before calling locator.all().

For more insights on handling flaky tests in Playwright, check out this blog post.


Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

Related Discord Threads

Related Questions

AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

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 luc@ray.run.