如果消息是由浏览器显示的,而不是添加到 DOM 中的内容,那么您将很难直接在 Playwright 中测试它。
您可以检查
required
属性是否存在,并相信浏览器将显示警告。
await page.locator('input#email[required]')
还有一个约束验证您可以应用
如果该元素是必需的,并且该元素的值为空字符串,则该元素将遭受 valueMissing 的影响,并且该元素将匹配
伪类。:invalid
await page.locator('input#email[required]:invalid')
可以但不建议测试。这是工作代码:
import { expect, test} from '@playwright/test';
test('has error 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 error = page.locator('input:invalid');
const validationMessage = await error.evaluate((element) => {
const input = element as HTMLInputElement
return input.validationMessage
})
expect(validationMessage).toContain("Please include an '@' in the email address. 'x' is missing an '@'.")
});
在此处阅读有关内置验证的更多信息: https://www.w3.org/WAI/tutorials/forms/validation/