One way to test the visibility of elements on a webpage is by playing with different conditions. For instance, when visiting Playwright's homepage, you may expect an element with the class .navbar__brand to be visible while also expecting an element with the class .notexists NOT to be visible (meaning it doesn't exist). Here's how you can implement these tests:
test('element does exist @pass', async ({ page }) => {
await page.goto('https://playwright.dev/');
const locator = await page.locator('.navbar__brand').isVisible();
expect(locator).toBeTruthy();
});
test('element does NOT exist @fail', async ({ page }) => {
await page.goto('https://playwright.dev/');
const locator = await page.locator('.notexists').isVisible();
expect(locator).toBeTruthy();
});
You could achieve the same results using a slightly different syntax:
test('element does exist @pass', async ({ page }) => {
await page.goto('https://playwright.dev/');
expect(await page.locator('.navbar__brand').isVisible()).toBe(true);
});
test('element does NOT exist @fail', async ({ page }) => {
await page.goto('https://playwright.dev/');
expect(await page.locator('.notexists').isVisible()).toBe(true);
});
Remember, the conditions you set for elements depend on your specific testing needs. You have the flexibility to assert various properties like visibility or presence in the DOM using if/else statements and boolean assertions like toBe(true)/toBe(false) or toBeTruthy()/toBeFalsy(). These methods might not be the most elegant, but they can definitely be useful in your testing scenarios.