Playwright Assertions

Profile picture for user arilio666

The playwright has assertions, too. Like any other automation, tool assertions are essential when we want to confirm, verify, or evaluate some elements or texts with comparison.

Assertions play a vital role in playwright. The Playwright test used expect library for test assertions, and the same library provides us with numerous matchers like toEqual, toContain, toMatch, etc.

There are many assertions down the way, but this article is about understanding how assertions work in playwright and getting a piece of proper knowledge about them, for example.

Let us further see some real-time assertions in the playwright with some good examples.

We will be practicing on the programsbuzz site.

toHaveText:

  • So toHaveText, when used in playwright, provides the actual text you want to verify with that includes blank spaces.
  • It needs to be precise when specifying the text.
const {test, expect} = require('@playwright/test');
test('Autopract Title Assertion', async ({page})=> 
{

await page.goto("https://www.programsbuzz.com/");
await expect(page.locator('a[href="/ask-doubt"]')).toHaveText('          Ask Doubt        ')


});

  • We can see that it has verified the text and returned true that it has the specified text in that selector.

toContainText:

  • Unlike toHaveText toContainText, when specified with the partial text, it should verify it will assert and confirm its presence.
  • You don't need to provide the exact text like toHaveText.
const {test, expect} = require('@playwright/test');
test('Autopract Title Assertion', async ({page})=> 
{

await page.goto("https://www.programsbuzz.com/");
await expect(page.locator('a[href="/ask-doubt"]')).toContainText('Ask')


});

  • So it has been asserted successfully.

Negative Matchers:

  • There is a way we can tell the playwright to assert negatively, meaning verifying text that it should not be there.
const {test, expect} = require('@playwright/test');
test('Autopract Title Assertion', async ({page})=> 
{

await page.goto("https://www.programsbuzz.com/");

await expect(page.locator('a[href="/ask-doubt"]')).not.toContainText('log')


});
  • So we are asking the playwright to assert the selector provided does not contain the text log.