Playwright Custom Expect Message

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.

Mon, 06/13/2022 - 14:37

Authored by

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.

Video Tutorial: Playwright Custom Expect Message

Tags