Assert with expect

Web-first assertions that retry: toHaveText, toContainText, toHaveAttribute.

expect() asserts on a locator, not on a value you pulled out of one. That is what makes it survive a slow page: it re-checks until the condition holds or the timeout runs out.

Run it

bash
php content/examples/expect.php

Expected result: the script exits successfully after asserting the page heading, paragraph text, and link attributes. If one assertion cannot become true, the script fails with the assertion error.

Basic assertion

php
use function Playwright\Testing\expect;

expect($page->locator('h1'))->toHaveText('Example Domain');

Compare with assertSame('Example Domain', $page->locator('h1')->textContent()), which reads the DOM once and fails the moment the app is slower than usual.

Chaining locators

An assertion takes any locator, including one narrowed from another:

php
$paragraphs = $page->locator('h1 ~ p');

expect($paragraphs->first())->toContainText('illustrative examples');
expect($paragraphs->locator('a'))->toHaveAttribute('href', 'https://www.iana.org/domains/example');

Negating

Any assertion inverts with not():

php
expect($page->locator('.error'))->not()->toBeVisible();

Controlling the wait

withTimeout() overrides the wait for one assertion, in milliseconds:

php
expect($page->locator('.slow-widget'))->withTimeout(10_000)->toBeVisible();

The assertions cheatsheet lists all of them. To run assertions inside a test suite rather than a script, see Testing with PHPUnit.

What it demonstrates

  • expect() retries browser state.
  • Locator assertions are safer than reading text once.
  • not() negates the next assertion.
  • withTimeout() changes one assertion budget.

Go next

Source

expect.php
php
<?php

declare(strict_types=1);

/*
 * This file is part of the community-maintained Playwright PHP project.
 * It is not affiliated with or endorsed by Microsoft.
 *
 * (c) 2025-Present - Playwright PHP - https://github.com/playwright-php
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

require __DIR__.'/../../vendor/autoload.php';

use Playwright\Playwright;

use function Playwright\Testing\expect;

$context = Playwright::chromium();
$page = $context->newPage();
$page->goto('https://example.com');

expect($page->locator('h1'))->toHaveText('Example Domain');

$paragraphs = $page->locator('h1 ~ p');

expect($paragraphs->first())->toContainText('illustrative examples');
expect($paragraphs->locator('a'))->toHaveAttribute('href', 'https://www.iana.org/domains/example');

$context->close();