15

I'm trying to get an element's attribute in a test. My test looks like this:

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);    
});

When I run this, I can see that the minlength value is 0. This is because _attribute is null. However, I don't understand why. field is a Locator. But, I can't seem to get the attribute or it's value. What am I doing wrong?

hardkoded
  • 18,915
  • 3
  • 52
  • 64
Dev
  • 921
  • 4
  • 14
  • 31
  • Are you sure that the initial value of `minlength` in your webpage is `5`? Or is it being set dynamically after the page is loaded? To be sure, you can try to change the locator function to evalaute and see how it results. `const _attribute = await page.evaluate(() => document.querySelector("#emailAddress").getAttribute("minlength"))`. And log it to see if it still returns `null`. – archon Mar 02 '22 at 16:30
  • @archon Thanks for the response. When I log the result of `await page.evaluable(() => document.querySelector('#emailAddress'));`, I see `null`. I have manually navigated to `http://localhost:8080` to ensure I'm trying to visit a running site (which I am). I also verified that an `input` element with an `id` of `emailAddress` exists on the page. What could I be doing wrong? – Dev Mar 02 '22 at 18:15
  • My guess is that the `minlength` attribute is set dynamically by javascript, after the webpage is loaded. And what happens is that playwright is picking the element before `minlength` assigned. You can try changing the `page.goto` function with `page.goto(url, { waitUntil: "networkidle" })`. If waiting until networkidle doesn't resolve your issue, you can try putting a manual timeout with settimeout before running the locator method to see if it's caused because of this. – archon Mar 02 '22 at 18:26

2 Answers2

20

This is the same but uses a native PlayWright function for getting attribute values

const inputElement = page.locator('#emailAddress');
const minLength = await inputElement.getAttribute('minLength');
6

The following worked for me

const inputElement = page.locator('#emailAddress');
minLength = await inputElement.evaluate(e => (e as HTMLInputElement).minLength);
typetetris
  • 4,586
  • 16
  • 31