Testing validation

Assert the error from the field

When a field points at its error with aria-describedby, assert the error through the field. The test then also proves the two are connected.

await expect(page.getByLabel('Email')).toHaveAccessibleDescription('Email address is required.');

Boundary values, one test each

Rules break at their edges: 17, 18, 100 and 101 for an age between 18 and 100. Loop over the cases to make one test per value, each with its own name in the report.

for (const { age, valid } of [{ age: '17', valid: false }, { age: '18', valid: true }]) {
  test(`age ${age} is ${valid ? 'accepted' : 'rejected'}`, async ({ page }) => { … });
}

Errors that appear when you leave a field

fill() does not move focus away. Press Tab, or call blur(), to trigger checks that run on blur. A check that asks the server can be mocked like any request:

await page.route('**/api/usernames/*', (route) =>
  route.fulfill({ json: { username: 'ada', available: false } })
);
await page.getByLabel('Username').fill('ada');
await page.getByLabel('Username').blur();

The browser's own validation

Without noValidate, the browser blocks the submit and shows its own bubble. That bubble is not part of the page: read the field's validity and validationMessage instead, or match :invalid.

const teamName = page.getByLabel('Team name');
expect(await teamName.evaluate((input: HTMLInputElement) => input.validity.valueMissing)).toBe(true);
await expect(page.locator('input:invalid')).toHaveCount(2);
The wording of validationMessage depends on the browser and its language. Assert the validity flags, not the text.

Registration Form

Some emails are already registered, for example taken@example.com. Only the server knows.

Sign-up with live checks

The username is checked when you leave the field. The password rules update as you type.

  • Not met: At least 8 characters
  • Not met: A number
  • Not met: An uppercase letter

Browser validation

This form uses the browser's built-in checks. Submit it empty to see them.