Skip to contentPlayForge

How do I assert that an element has a CSS class in Playwright?

Written by Jatin Thacker, Automation Architect · Updated

To check one class among several, use await expect(locator).toContainClass('name'). toHaveClass('...') with a string must match the whole class attribute, so use it only when you mean every class, or pass it a regular expression.

This answer is one piece of Chapter 11: Assertions.

  • Web-First Assertions Cookbook
  • Retry & Polling Patterns
  • Visual Regression Testing
  • Making a Failure Explain Itself

The common mistake is writing toHaveClass('badge--packed') for an element whose class attribute is badge badge--packed. With a string, toHaveClass() compares against the entire attribute, so that check fails even though the class is there.

There are three ways to get it right, and the example uses all three on the status badge in the first order row:

  • toHaveClass('badge badge--packed') matches the full attribute exactly.
  • toHaveClass(/(^|\s)badge--packed(\s|$)/) matches one class with a regular expression. The (^|\s) and (\s|$) parts stop badge--packed matching inside a longer class name.
  • toContainClass('badge--packed') checks that the listed classes are present, in any order. The Playwright docs point to it for exactly this case.

All three retry, so they wait for a class added by script. Assert on classes only when the class carries meaning, as a status badge's does. Classes that exist only for styling change often and make brittle tests.

class.spec.js(https://practice.learnplayforge.com)
import { test, expect } from '@playwright/test'; test('the first order carries the packed badge class', async ({ page }) => { await page.goto('/orders.html?mock=static&seed=42&autologin=1'); const badge = page.getByRole('row').filter({ hasText: 'ORD-4100' }) .getByTestId('cell-status').locator('span'); await expect(badge).toHaveClass('badge badge--packed'); // the whole class attribute await expect(badge).toHaveClass(/(^|\s)badge--packed(\s|$)/); // one class, by regex await expect(badge).toContainClass('badge--packed'); // one class, by name });
Output
1 passed (2.3s)
Test yourself
An element has class="badge badge--packed". What does await expect(badge).toHaveClass('badge--packed') do?

AI can write the test now. The job is knowing whether it checks anything. That's what the course teaches, one chapter at a time.

163 lessons · 226 drills · start free

← All questions

Training a team? Talk to us.