Testing a form

Find fields by their label

getByLabel() finds an input the way a user does: by the text next to it. fill() replaces the whole value, so you never need to clear a field first.

await page.getByLabel('Username').fill('TedBuckland');
await page.getByLabel('Password').fill('Alligator3');
await page.getByLabel('Password').press('Enter');   // submits, like a user

Assert what the user sees, and what a screen reader hears

An error message is not enough on its own: check the field is marked invalid too. aria-invalid is what assistive technology announces.

await expect(page.getByLabel('Username')).toHaveAttribute('aria-invalid', 'true');
await expect(page.getByLabel('Password')).toHaveAttribute('type', 'password');
A toggle such as "Show password" keeps its name and reports its state with aria-pressed. Assert that, and the field's type, rather than the button's text.

Waiting out a lockout

Three wrong passwords lock the form for 30 seconds. A test should not wait 30 real seconds. Install a fake clock before the page loads, then move it forward:

await page.clock.install();
await page.goto('/forms/login');
// … three failed attempts …
await page.clock.fastForward('00:31');
await expect(page.getByRole('button', { name: 'Login' })).toBeEnabled();

Login

Demo Credentials:

Login: TedBuckland

Password: Alligator3