Attributes, properties and data attributes

Two different things with the same name

  • An attribute is what is written in the HTML: <input value="Initial value">. It is the starting value.
  • A property lives on the element object in the browser: input.value. It is the current value, and it changes as the user types.
const nickname = page.getByLabel('Nickname');
await nickname.fill('Neo');

expect(await nickname.getAttribute('value')).toBe('Initial value'); // the HTML
await expect(nickname).toHaveValue('Neo');                          // what the user sees
await expect(nickname).toHaveJSProperty('value', 'Neo');            // the property

The same goes for checkboxes: the checked attribute stays in the HTML after the user unchecks the box.

const updates = page.getByLabel('Send me product updates');
await updates.uncheck();

await expect(updates).toHaveAttribute('checked'); // still in the HTML
await expect(updates).not.toBeChecked();         // but not checked
await expect(updates).toHaveJSProperty('checked', false);

Which one should a test use?

Almost always the one that reflects what the user sees: toHaveValue(), toBeChecked(), or toHaveJSProperty() for anything else. getAttribute() tells you what the page started with.

Checking that an attribute is present

Some attributes matter just by being there, such as required, readonly and hidden. Leave out the value to check only that it is present:

await expect(page.getByLabel('Work email')).toHaveAttribute('required');
await expect(page.getByLabel('Nickname')).not.toHaveAttribute('required');

Relative links become absolute

const link = page.getByRole('link', { name: 'Back to Content & Attributes' });

expect(await link.getAttribute('href')).toBe('/content/attributes');
expect(await link.evaluate((a: HTMLAnchorElement) => a.href)).toBe(
  new URL('/content/attributes', page.url()).href
);

data-* attributes

Apps often store state in data-* attributes. data-testid is one of them. Assert one at a time, or read them all through the element's dataset:

const product = page.getByRole('article', { name: 'Wireless Mouse' });

await page.getByRole('button', { name: 'Buy one' }).click();
await expect(product).toHaveAttribute('data-stock', '2');

const data = await product.evaluate((el) => ({ ...el.dataset }));
expect(data).toEqual({ sku: 'QA-1042', stock: '2', status: 'in-stock' });

Typed value

Type something, then compare the attribute with the value.

Checked state

Starts checked in the HTML. Uncheck it and compare.

Data attributes

Wireless Mouse

3 left in stock