Home > Software engineering >  Playwright - check a Locator has only 1 element
Playwright - check a Locator has only 1 element

Time:12-22

I'm using Playwright to locate all the option roles like so:

const autocompleteItem = page.getByRole('option');

And now i just want to check it return 1 element:

expect(autocompleteItem).toHaveLength(1);

But i get an error as the locator return an object and not an array...

Matcher error: received value must have a length property whose value must be a number

Received has type: object Received has value: {"_frame": {"_guid": "frame@da0ab90a509c7446b8566c8b7da167b5", "_type": "Frame"}, "_selector": "internal:role=option"} at tests/e2e/playwright/index.test.ts:17:30

I need an explicit check this locator return 1 element... Is it possible?

CodePudding user response:

autocompletion is a Locator object which has a .count() method.

You would await it and test the result

const autocompleteItem = page.getByRole('option');
const count = await autocompleteItem.count()
expect(count).to.eq(1)

CodePudding user response:

You can use the web first assertion toHaveCount() on the locator:

const autocompleteItem = page.getByRole('option');
await expect(autoCompleteItem).toHaveCount(1);
  • Related