Playwright Custom Expect Message

Profile picture for user arilio666

We can specify a custom message as a second argument to the expect function. This message will also display as a title in Test Steps and an error message in the Errors section of the report. Custom Message will show in Test Steps no matter whether your test pass or fail.

Table of Content

  1. Expect without Custom Message
  2. Expect with Custom Message
  3. Soft Assertion with Custom Message
  4. Video Tutorial

1. Expect without Custom Message

Selector is incorrect so expect will fail.

Code:

test.only('custom expect message', async({page})=>{
    await page.goto('https://www.programsbuzz.com/')
    await expect(page.locator("img[alt='Home1']")).toBeVisible();
})

Errors Section:

expect without custom expect message

Test Steps:

Expect without Custom Message 

2. Expect with Custom Message 

For the same code, this time we have added custom message.

Code:

test.only('custom expect message', async({page})=>{
    await page.goto('https://www.programsbuzz.com/')
    await expect(page.locator("img[alt='Home1']"),'Checking Element Visibility.').toBeVisible();
})

Errors Section:

​​custom expect message error section

Compare the output with the previous section when the custom expect message was not added.

Test Steps:

custom expect message

Notice here expect.toBeVisible replaced with the custom message we have given.

3. Soft Assertion with Custom Message

In the same way, you can also add a custom message to soft assertions as well. Here, the first assertion will pass, and the second will fail.

Code

test.only('custom expect message', async({page})=>{
    await page.goto('https://www.programsbuzz.com/')
    const locator = page.locator('ul.we-mega-menu-ul>li').nth(-1);
    
    await expect.soft(locator,'Verify Element Data Element Attribute Value.').toHaveAttribute('data-element-type1','we-mega-menu-li');
    await expect.soft(locator, 'Verify Element Class Exist.').toHaveClass('we-mega-menu-li')
})

Errors Section

custom expect message for soft assertion

Test Steps

custom expect message in test steps for soft assertions

Observe that the message is displaying no matter expect fail or pass.

Video Tutorial: Playwright Custom Expect Message