playwrightrequiredhtml-inputplaywright-test

playwright-test: test that input is required


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."

Chrome input warning saying "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.


Solution

  • 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 :invalid pseudo class.

    await page.locator('input#email[required]:invalid')