'How to specify text even more?
I would like to know if there is a way to specify the text selection even more than text="text"? Specification of playwright is no enough, and moreover I cannot use other selectors due to the structure of tests (there are more than several thousands of assertions, so I make custom commands)
The problem is the following: on the web page that I am testing there are several pieces of text locators, all of which contain the same text fragment. For example when I use "'The Exact text'" I get selectors with text 'The Exact text' and 'Some Other TextThe Exact text'.
Solution 1:[1]
https://playwright.dev/docs/selectors#text-selector
You could use JavaScript regex to get what You need as it is stated in documentation here are few examples:
/Log\s*in/i - body can be a JavaScript-like regex wrapped in / symbols. For example, text=/Log\s*in/i matches Login and log IN.
await page.click('text=/Log\\s*in/i');
Or Use text-matches:
#nav-bar :text-matches("reg?ex", "i") - the :text-matches() pseudo-class can be used inside a css selector, for regex-based match. This example is equivalent to text=/reg?ex/i, but inside the #nav-bar element.
To get exact match of text use:
await page.locator(':text-is("The Exact text")')
Solution 2:[2]
Using first() should be enough to assert the test.
await expect(page.locator('text="The Exact Text"').first()).toBeVisible();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Cathal Mac Donnacha |
