What is the method to check if multiple elements contain the same text in Playwright?


Using toContainText in Playwright

Playwright's toContainText method is a handy tool for asserting that multiple elements contain the same text. It checks if a locator points to an element or elements that contain the specified text.

Creating a Locator

First, create a locator for the elements you want to assert. If you have a list of items with <li> tags inside a <ul> element, create a locator like this:

const locator = page.locator('ul > li');

Using toContainText

Next, use the toContainText method on the locator and pass in an array of expected texts. The method checks if any of the elements matched by the locator contain any of the expected texts.

await expect(locator).toContainText(['Text 1', 'Text 2', 'Text 3']);

In this example, we're asserting that all three texts ('Text 1', 'Text 2', and 'Text 3') are present in some order within the matched elements.

Using Regular Expressions

You can also use regular expressions as expected values. For example:

await expect(locator).toContainText([/text \d/i]);

Here, we're using a regular expression /text \d/i which matches any text containing "text" followed by a digit (case-insensitive).

By using toContainText with locators and arrays of expected texts or regular expressions, you can easily assert that multiple elements contain specific text without specifying their exact number or order.


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.