Rayrun

What is the difference in behavior and execution order between 'await expect(page.locator)' and 'expect(await page.locator)' in Playwright Test?

Answer

Understanding await expect(page.locator) and expect(await page.locator)

Let's break down the differences between await expect(page.locator) and expect(await page.locator) in @playwright/test.

await expect(page.locator)

Here, the code waits for the page locator to resolve before executing the assertion. This means that Playwright Test will keep checking the node with the specified selector until it meets a certain condition, like having a specific text value. It will keep re-fetching and checking the node until either the condition is met or a timeout is reached. You can set the timeout as an argument or configure it globally via test config.

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

test('await expect(page.locator)', async ({ page }) => {
  await page.goto('https://ray.run/');
  await expect(page.locator('.my-selector')).toHaveText('Hello World');
});

expect(await page.locator)

In this case, the code first resolves the page locator and then applies an assertion. Playwright Test fetches and checks the node returned by page locator immediately, without waiting for any asynchronous operations to complete.

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

test('expect(await page.locator)', async ({ page }) => {
  await page.goto('https://ray.run/');
  const locator = page.locator('.my-selector');
  expect(await locator).toHaveText('Hello World');
});

In summary, await expect(page.locator) allows you to wait for specific conditions on elements with configurable timeouts, while expect(await page.locator) performs assertions immediately without waiting for asynchronous operations to complete.

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 luc@ray.run.