'How to check if an element is in the document with playwright?

I want to test if an element had been rendered. So I want expect that if is present. Is there a command for this?

await page.goto(‘<http://localhost:3000/>');
const logo = await page.$(‘.logo’)

// expect(logo.toBeInDocument())


Solution 1:[1]

If you query one element with page.$(), you can simply use:

const logo = await page.$('.logo');
if (logo) {

}

Similarly if you query multiple elements with page.$$():

const logo = await page.$$('.logo');
if (logo) {

}

Since this example returns (after awaiting) an array of element handles, you can also use property length in the condition:

const logo = await page.$$('.logo');
if (logo.length) {

}

The key in all these examples is to await the promise that page.$() and page.$$() return.

Solution 2:[2]

Since the use of ElementHandle (page.$(), page.$$()) is discouraged by the Playwright Team, you could use the Locator object and the count() method:

expect(await page.locator('data-testid=exists').count()).toBeTruthy();
expect(await page.locator('data-testid=doesnt-exist').count()).toBeFalsy();

If you want to check if the element is rendered (I assume you mean visible) you could use the toBeVisible assertion:

await expect(page.locator('data-testid=is-visible')).toBeVisible();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 pavelsaman
Solution 2 zeekrey