How do I create custom filters and locators in Playwright/test?


Sure, you can create a locator in @playwright/test to check for messages after a specific time. You can also write custom filters with your own functions.

To filter locators by text, use the locator.filter() method. This lets you search for a string or regular expression inside an element.

Here's how you can chain methods to create locators and apply filters:

await page.getByRole('listitem')
  .filter({ hasText: 'Product 2' })
  .getByRole('button', { name: 'Add to cart' })

In this example, we first locate the list item with role 'listitem'. Then we apply the filter { hasText: 'Product 2' } to only select elements that have the text "Product 2". Finally, we locate the button with role 'button' and name 'Add to cart', and perform an action like clicking it.

You can also use regular expressions as filters. For instance:

await page.getByRole('listitem')
  .filter({ hasText: /Product 2/ })
  .getByRole('button', { name: 'Add to cart' })

This will match any element that contains "Product 2" in its text.

Additionally, you can filter by not having text or not having child/descendant elements matching another locator. Here's an example:

// Filter by not having text
await expect(page.getByRole('listitem').filter({ hasNotText: 'Out of stock' })).toHaveCount(5);

// Filter by not having child/descendant
await expect(page.getByRole('listitem').filter({ hasNot: page.getByText('Product 2') })).toHaveCount(1);

In the first example, we filter out elements that have the text "Out of stock". In the second example, we filter out elements that have a descendant matching the locator page.getByText('Product 2').

Playwright provides powerful options for creating custom filters and performing actions based on specific conditions. You can combine different locators and filters to achieve your desired functionality.


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.