如何在 Playwright 测试中获取元素的属性?

How to get an element's attribute in a Playwright test?

我正在尝试在测试中获取元素的属性。我的测试看起来像这样:

test(`Should be at least 5 characters long`, async({ page }) => {
  await page.goto('http://localhost:8080');
  const field = await page.locator('id=emailAddress');

  const _attribute = await field.getAttribute('minlength');
  const minlength = Number(_attribute);

  await expect(minlength).toBeGreaterThanOrEqual(5);    
});

当我 运行 时,我可以看到 minlength 值为 0。这是因为 _attributenull。但是,我不明白为什么。 field 是一个 Locator。但是,我似乎无法获得该属性或它的价值。我做错了什么?

以下对我有用

const inputElement = page.locator('#emailAddress');
minLength = await inputElement.evaluate(e => (e as HTMLInputElement).minLength);