Friday, April 11, 2025

Custom expect message in playwright

 In Playwright, if you want to customize the error message when an expect assertion fails, you can use the message option available in many of the expect methods.



You can specify a custom expect message as a second argument to the expect function, for example:

await expect(page.getByRole('heading', { name: 'Installations' }) ,'Heading Should be Visible.').toBeVisible();


This message will be shown in reporters, both for passing and failing expects, providing more context about the assertion.

1. When expect passes, you might see a successful step like this:


Example

// @ts-check
import { test, expect } from '@playwright/test';
import { chromium } from 'playwright';

test('get started link', async () => {

  const browser = await chromium.launchPersistentContext('', { headless: false, channel: 'chromium' });
  const page = await browser.newPage();
  await page.goto('https://playwright.dev/');

  // Click the get started link.
  await page.getByRole('link', { name: 'Get started' }).click();

  // Expects page to have a heading with the name of Installation.
  await expect(page.getByRole('heading', { name: 'Installation' }) ,'Heading Should be Visible.').toBeVisible();  

});

Output :

2. When expect fails, the error would look like this:

Example :

// @ts-check
import { test, expect } from '@playwright/test';
import { chromium } from 'playwright';

test('get started link', async () => {

  const browser = await chromium.launchPersistentContext('', { headless: false, channel: 'chromium' });
  const page = await browser.newPage();
  await page.goto('https://playwright.dev/');

  // Click the get started link.
  await page.getByRole('link', { name: 'Get started' }).click();

  // Expects page to have a heading with the name of Installation.
  await expect(page.getByRole('heading', { name: 'Installations' }) ,'Heading Should be Visible.').toBeVisible();  

});

Output :

Error: Heading Should be Visible.

Timed out 5000ms waiting for expect(locator).toBeVisible()

Locator: getByRole('heading', { name: 'Installations' })
Expected: visible
Received: <element(s) not found>
Call log:
  - Heading Should be Visible. with timeout 5000ms
  - waiting for getByRole('heading', { name: 'Installations' })


  29 |
  30 |   // Expects page to have a heading with the name of Installation.
> 31 |   await expect(page.getByRole('heading', { name: 'Installations' }) ,'Heading Should be Visible.').toBeVisible();
     |                                                                                                    ^
  32 |
  33 |   
  34 |   
    at D:\playwright Project\Playwright-tutorial\tests\demo.spec.js:31:100


NOTE : Soft assertions also support custom message:

expect.soft(value, 'my soft assertion').toBe("skptricks");


No comments:

Post a Comment