Skip to contentPlayForge

How do I assert an attribute value in Playwright?

Written by Jatin Thacker, Automation Architect · Updated

Use await expect(locator).toHaveAttribute('name', 'value'), which retries until the attribute has that value. Pass only the name, toHaveAttribute('name'), to check that the attribute is present at all.

This answer is one piece of Chapter 11: Assertions.

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

Many states never show up as visible text. A sorted column, the current page in a menu, an invalid field: these are often recorded in attributes such as aria-sort, aria-current and aria-invalid. toHaveAttribute() checks them, and like all web-first assertions it waits for a script to change the value. The expected value can be a string or a regular expression.

In the example, the orders table's Customer header starts with aria-sort="none". The test clicks the sort button in that header, then asserts that the header now reads aria-sort="ascending". A check written as expect(await header.getAttribute('aria-sort')).toBe(...) is a non-retrying assertion: it reads once, possibly before the page updates. toHaveAttribute() retries until it matches.

The last line checks the navigation: the Orders link carries aria-current="page" because it is the page you are on.

Attributes like these are good assertion targets because they describe state for screen readers, so the app has a reason to keep them correct.

attribute.spec.js(https://practice.learnplayforge.com)
import { test, expect } from '@playwright/test'; test('sorting by customer sets aria-sort on the header', async ({ page }) => { await page.goto('/orders.html?mock=static&seed=42&autologin=1'); const header = page.getByTestId('th-customer'); await expect(header).toHaveAttribute('aria-sort', 'none'); await header.getByRole('button', { name: /^Customer/ }).click(); await expect(header).toHaveAttribute('aria-sort', 'ascending'); await expect(page.getByRole('link', { name: 'Orders', exact: true })) .toHaveAttribute('aria-current', 'page'); });
Output
1 passed (2.3s)
Test yourself
Which assertion checks only that an aria-current attribute exists, whatever its value?

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.