How to get the text of a h1 headline with playwright?

Viewed 3239

I want to test if a headline has a certain text. Is there a command for this?

await page.goto(‘<http://localhost:3000/>');


expect(await page.$("data-testid=headline")).toBe("my headline")
2 Answers

page.$() only returns: <Promise<null|ElementHandle>>

You should use innerText or innerHtml like this:

expect(await page.innerText("data-testid=headline")).toBe("my headline")

expect(await page.innerHtml("data-testid=headline")).toBe("my headline")

These two methods will return <Promise<string>>

innerText only return the text, while innerHtml will return all things inside it. For example:

<p>
  <a>Hey</a>
  Helloworld!
</p>

page.innerText("p") will return Helloworld!.

But page.innerHtml("p") will return <a>Hey</a>Helloworld!

Hope my answer can help you.

Related