Wireless Mouse
3 left in stock
What the HTML said when the page loaded is not always what the element holds now.
<input value="Initial value">. It is the starting value.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 propertyThe 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);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.
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');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
);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' });Type something, then compare the attribute with the value.
Starts checked in the HTML. Uncheck it and compare.
3 left in stock
Read the guide: Playwright cheat sheet: locators, actions and assertions