Rayrun
← Back to Discord Forum

asserstion for first child element

how to assert contain text for first element?

This thread is trying to answer question "How to assert contain text for first element?"

4 replies
bububu8615
bububu8615

await expect(locator.first()).toContainText(expectedText)

thanks!

how can i check if the element contain first func?

? what do you mean contains first function? first is a method on a locator...? Woud assert what Bububu is more a shorthand pseudo code...

Answer

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!

Related Discord Threads

TwitterGitHubLinkedIn
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.