Search code examples
arrayse2e-testingplaywright

Playwright - check a Locator has only 1 element


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?


Solution

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

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