Rayrun

What is the method to verify if a specific string is present in an h1 element using Playwright?

Answer

Checking if an h1 Element Contains a Specific String with Playwright

First, let's locate the h1 element. We'll use the page.locator() method and specify a CSS selector that matches our h1 element. Let's say our h1 element has an id of "title". Here's how you can locate it:

const titleElement = await page.locator('#title');

Next, we'll get the text content of the h1 element using the locator.textContent() method. This method returns a Promise that resolves to a string containing all of the text within the h1 element.

const titleText = await titleElement.textContent();

Now, let's check if this text contains "hello, world". We'll use 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".');
}

And that's it! You've just checked if an h1 element includes a specific string using Playwright. Remember, the steps are:

  1. Locate the h1 element using page.locator().
  2. Get its text content using locator.textContent().
  3. Use String.prototype.includes() to check for your desired substring.

For more tips and tricks on using Playwright, check out our blog post on Mastering Playwright Test Automation: Your Comprehensive Cheat Sheet.

References

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 Questions

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.