One common task in UI testing is checking whether an element exists on the page, whether it’s a button, a modal, or a dynamic message.
Here’s a quick guide on how to do that efficiently in Playwright.
✅ Check presence of element using page.$()
The simplest way to check if an element exists is by using the $
method. This returns a null
if the element is not found.
const element = await page.$('#my-element'); if (element) { console.log('Element exists!'); } else { console.log('Element does not exist.'); }
✅ Check presence of element using locator().count()
The recommended way in modern Playwright code is using locator() and checking the count.
const count = await page.locator('#my-element').count(); if (count > 0) { console.log('Element is present.'); } else { console.log('Element not found.'); }
// Exactly one element matching the locator is present await expect(page.locator('#my-element')).toHaveCount(1);
2. To verify the absence of an element, proceed as follows:
// Exactly one element matching the locator is present await expect(page.locator('#my-element')).toHaveCount(0);
✅ Check presence of element using element visibility
To ascertain an element's visibility, apply the isVisible() method to a locator:
const element = await page.locator('#my-element').isVisible(); if (element) { console.log('Element exists!'); } else { console.log('Element does not exist.'); }
1. For direct visibility assertions, utilize toBeVisible():
await expect(page.locator('#my-element')).toBeVisible();
2. To assert the inverse, that an element is hidden, use the not property:
await expect(page.locator('#my-element')).not.toBeVisible();
This is a quick guide on how to check presence of element efficiently in Playwright.
No comments:
Post a Comment