I have an input for a login form that is required:
<input
autoComplete="email"
defaultValue={email}
disabled={state === 'submitting'}
id="email"
name="email"
placeholder={t('user-authentication:email-placeholder')}
required // HERE!
type="email"
/>
How can I test that the input is required with Playwright? My native browser warning in Chromium is: "Please fill in this field."

Is there a way to check / assert for this warning in Playwright? Or another way to test that the input is required?
I tried writing nothing in the input with .fill('') and then pressing enter with page.keyboard.press('Enter'), but those did not cause the warning to show up.
If the message is displayed by the browser and not something added to the DOM, you would struggle to test it directly in Playwright.
You could check the the required attribute is present, and trust that the browser is going to display the warning.
await page.locator('input#email[required]')
There's also a Constraint validation you could apply
If the element is required and the element's value is the empty string, then the element is suffering from valueMissing and the element will match the
:invalidpseudo class.
await page.locator('input#email[required]:invalid')
Here is the working Playwright code of testing browser native warning message (tested for Chrome):
import { expect, test} from '@playwright/test';
test('has warning message presented', async ({ page }) => {
await page.goto('https://q94u5.csb.app/');
const email = page.getByRole('textbox')
const submit = page.getByRole('button', { name: 'Submit' });
await email.fill('x');
await submit.click();
const validationMessage = await email.evaluate((element) => {
const input = element as HTMLInputElement
return input.validationMessage
})
expect(validationMessage).toContain("Please include an '@' in the email address. 'x' is missing an '@'.")
});
As you can see, you can catch validationMessage in Playwright but is not recommended to test it. It is browser responsibility to deliver this element (and it is not responsibility of the webpage itself).
Read more about build-in validation here: https://www.w3.org/WAI/tutorials/forms/validation/
More elements information can be extracted this way: https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation and go to chapter Validating forms using JavaScript to check available methods
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With