Rayrun

What is the difference between toBeVisible() and isVisible() in Playwright?

Answer

Understanding toBeVisible() and not.toBeVisible() in Playwright

In Playwright, toBeVisible() and not.toBeVisible() are web first assertions. They ensure your tests are reliable by waiting for expected conditions to be met before proceeding.

The toBeVisible() Assertion

When you use toBeVisible(), Playwright waits until the expected condition is met. For instance, if your test clicks a button and expects an alert message to appear, toBeVisible() waits for the alert message to be visible before proceeding.

import { test } from '@playwright/test';

test('alert should be visible', async ({ page }) => {
  await page.goto('https://ray.run');
  await page.click('#alertButton');
  await expect(page.locator('#alertMessage')).toBeVisible();
});

The not.toBeVisible() Assertion

On the contrary, manual assertions like isVisible() don't wait for any condition. They simply check if the locator is there and return immediately. This means that if you use expect(await page.getByText('welcome').isVisible()).toBe(true), it may return true even if the element is not actually visible.

import { test } from '@playwright/test';

test('welcome text should not be visible', async ({ page }) => {
  await page.goto('https://ray.run');
  await expect(await page.getByText('welcome').isVisible()).toBe(true);
});

In summary, toBeVisible() and not.toBeVisible() pass because they utilize web first assertions provided by Playwright. They ensure your tests wait until expected conditions are met before proceeding.

References

Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

Related Discord Threads

Related Questions

TwitterGitHubLinkedIn
AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email [email protected].