Skip to main content

Playwright Assertions

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.
Tags
Submitted by arilio666 on June 9, 2022

Ashwin is working with iVagus as a Technical Lead. He has experience in various technologies like Cypress, JavaScript, TypeScript, Rest Assured, Selenium, Cucumber, and Java.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.