Playwright Assert Element To Have Class

While browsing the website, if you will inspect elements, you will find that classes are added or removed from an element or set of elements. To verify this scenario, you can use Playwright toHaveClass() method.

Table of Content

  1. Syntax
  2. Demo Website
  3. Assert class value using full match
  4. Assert class value using partial match
  5. Assert classes in a list of elements
  6. Video Tutorial

1. Syntax

expect(locator).toHaveClass(expected[, options])
  • expected: <string|RegExp|Array<string|RegExp>> Expected class or RegExp or a list of those.
  • options? <Object>
    • timeout? <number> Time to retry the assertion for. Defaults to timeout in TestConfig.expect. 
  • returns: <Promise<void>>

2. Demo Website

assert class values in playwright

  • For the demo, we will verify that two new classes  active and active-trail are added to the Ask Doubt list element after clicking on the Ask Doubt link. 
  • Also, we will verify the class values of the list of items in the top menu.

3. Assert class Value using full match

test.only("verify class", async({page})=>{
    await page.goto('https://www.programsbuzz.com/')
  
    const locator = page.locator('ul.we-mega-menu-ul>li').nth(-1);
    await locator.click()
    await expect(locator).toHaveClass('we-mega-menu-li active active-trail');
  })

After finding the Ask Doubt using the nth selector and -1 index for the last element of the list, and clicking on the Ask Doubt link,  we verified two more classes are added by giving all class values. 

4. Assert class Value using partial match

await expect(locator).toHaveClass(/active active-trail/);

You can also match using regular expressions and give newly added classes.

5. Assert Classes in a list of Elements

You can also verify classes in a list of elements using the array.

const topList = page.locator('ul.we-mega-menu-ul>li');
 await expect(topList).toHaveClass([/dropdown-menu/,/dropdown-menu/,/dropdown-menu/,/dropdown-menu/,/active active-trail/]);

Here we are verifying that the first four elements, Tutorials, Interview Questions, MCQ, and Certifications, contain class dropdown-menu and the last element, Ask Doubt, has active and active-trail classes.

Fri, 09/02/2022 - 16:55

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.

Playwright Verify Class Added or Removed

Tags