Assert Attribute Value in Playwright

Each element has associated attributes with it in HTML. For example, the image has src, width, and height attributes. Many other elements contain class, id, name, or other attributes. You can use the toHaveAttrribute assertion in the playwright to assert an attribute with its value.

Table of Content

  1. Syntax
  2. Demo Website
  3. Assert Attribute with its value
  4. Assert Attribute with partial value
  5. Assert Attribute with no value
  6. Video Tutorial

1. Syntax

expect(locator).toHaveAttribute(name, value[, options])
  • name: <string> Attribute name. 
  • value: <string|RegExp> Expected attribute value. 
  • options? <Object>
    • timeout? <number> Time to retry the assertion for. Defaults to timeout in TestConfig.expect. 
  • returns: <Promise<void>>

2. Demo Website

For demo let's verify attributes of Ask Doubt Link in top menu of ProgramsBuzz

Assert Attribute Value in Playwright

<li class="we-mega-menu-li" data-level="0" data-element-type="we-mega-menu-li" description="" data-id="94a4de27-81db-4e54-8897-3958f3d60ca9" data-submenu="0" hide-sub-when-collapse="" data-group="0" data-class="" data-icon="" data-caption="" data-alignsub="" data-target="">
      <a class="we-mega-menu-li" title="" href="/ask-doubt" target="">
      Ask Doubt    </a>
</li>

3. Assert Attribute with its value

test.only("verify attribute", async({page})=>{
    await page.goto('https://www.programsbuzz.com')

    const locator = page.locator('ul.we-mega-menu-ul>li').nth(-1);
    await expect(locator).toHaveAttribute('data-element-type','we-mega-menu-li');
})
  • Here using -1 in the nth selector, we are clicking on the last menu option, Ask Doubt in a list.
  • Using toHaveAttribute, we have verified that data-element-type has the value we-mega-menu-li.

4. Assert Attribute with partial value

await expect(locator).toHaveAttribute('data-element-type',/we-mega/);
  • Here, we have verified that the data-element-type contains a value that starts with we-mega.
  • Make sure you are not using quotes with slashes (//).

5. Assert Attribute with no value

Not all attributes have value, for example, data-class and data-icon. In that case, leave the value blank.

await expect(locator).toHaveAttribute('data-class','');
Wed, 08/31/2022 - 16:14

Authored by

Tarun Goswami, works as a Technical Lead at the well-known IT services company. With Over 11+ years of experience in Quality Assurance, he writes engaging and informative blogs in his spare time.

Video Tutorial: Verify Attribute Value in Playwright

Tags