First, you need to locate the h1 element. You can use Playwright's page.locator()
method with a CSS selector that matches the h1 element. Let's say your h1 element has an id of "title". Here's how you can locate it:
const titleElement = await page.locator('#title');
Next, get the text content of the h1 element using locator.textContent()
. This returns a Promise that resolves to a string containing all the text within the h1 element.
const titleText = await titleElement.textContent();
Finally, check if the text contains "hello, world" using JavaScript's String.prototype.includes()
method. This method returns true if the specified substring is found within the string.
if (titleText.includes('hello, world')) {
console.log('The title contains "hello, world"!');
} else {
console.log('The title does not contain "hello, world".');
}
So, to check if an h1 element includes a string "hello, world" using Playwright, you:
page.locator()
locator.textContent()
String.prototype.includes()
to check for the presence of the desired substring.For more insights on using Playwright, check out Understanding the Difference Between Locators and Selectors in @playwright/test.
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].