Sure, let's dive into how you can assert that the first element contains a specific text using @playwright/test.
First, you need to find the element. You can use page.locator()
or page.getByRole()
to do this. Once you have the locator, you can use the toContainText()
assertion.
Here's a quick example:
const locator = page.locator('ul > li'); // Find all list items
await expect(locator.first()).toContainText('Text 1'); // Check that first item contains 'Text 1'
In this code, locator.first()
selects the first item from the list of elements. Then, .toContainText('Text 1')
checks that this element contains 'Text 1'.
But what if you want to check multiple texts for different elements in order? You can pass an array of expected texts to toContainText()
. The elements will match the order of the expected array.
Here's how:
const locator = page.locator('ul > li'); // Find all list items
await expect(locator).toContainText(['Text 1', 'Text 2', 'Text 3']); // Check multiple texts in order
Playwright will check if each text value from the array matches an element from the list. If any of these checks fail, it means that one or more elements do not contain their expected texts.
Remember, these examples assume a certain DOM structure. You might need to adjust them based on your HTML markup. Happy testing!
If you still have questions, please ask a question and I will try to answer it.
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 [email protected].