Rayrun

What is the difference between expect and waitForSelector when checking element visibility in Playwright tests?

Answer

Checking Element Visibility with expect and waitForSelector

In @playwright/test, you can use expect and waitForSelector to check if elements are visible or hidden on a web page. Here's how they differ:

Using expect

expect is a test assertion that checks if an element is visible or hidden at a single point in time. It automatically waits for the element to become visible before making the assertion. If the element doesn't become visible within the configured timeout, the test fails.

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

test('Check element visibility with expect', async ({ page }) => {
  await page.goto('https://ray.run');
  await expect(page.locator('#element')).toBeVisible();
});

Using waitForSelector

waitForSelector waits for an element specified by a selector to satisfy a certain condition, such as becoming visible or hidden. If the selector already satisfies the condition, it returns immediately. Otherwise, it waits until the condition is satisfied or a timeout occurs.

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

test('Check element visibility with waitForSelector', async ({ page }) => {
  await page.goto('https://ray.run');
  await page.waitForSelector('#element', { state: 'visible' });
});

Key Differences

  • expect checks visibility at one point in time, while waitForSelector waits for the element to satisfy the specified condition.
  • If an element is initially hidden, using expect will fail immediately, whereas waitForSelector with a suitable timeout and state option will continue running until the condition is satisfied or a timeout occurs.

In summary, both expect and waitForSelector can check element visibility in Playwright tests. However, expect may lead to unexpected failures due to timing issues, while waitForSelector helps prevent such failures by waiting for elements to satisfy specific conditions.

Thank you!
Was this helpful?
Still have questions?

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

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].