Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
### Fixed
- Screenshots taken without a path use the extension of their `type` instead of always `.png` (#207)
- The `mask` option of `Page::screenshot()` and `Locator::screenshot()` covers the given locators instead of failing in the driver; other values throw `InvalidArgumentException` (#209)
- A locator assertion on a locator that resolves to several elements fails at once with Playwright's strict mode message instead of waiting for its timeout (#226)

## [1.6.0] - 2026-11-07

Expand Down
3 changes: 2 additions & 1 deletion src/Assertions/Failure/AssertionException.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ public function __construct(
string $message,
public readonly mixed $actual = null,
public readonly mixed $expected = null,
?\Throwable $previous = null,
) {
parent::__construct($message);
parent::__construct($message, 0, $previous);
}
}
22 changes: 19 additions & 3 deletions src/Assertions/Internal/AbstractAssertions.php
Original file line number Diff line number Diff line change
Expand Up @@ -117,12 +117,19 @@ private function runAssertion(
$pollIntervalMs = null === $options || null === $options->intervalMs ? $this->pollIntervalMs : $options->intervalMs;
$deadline = hrtime(true) + ($timeoutMs * 1_000_000);

$message = null === $options || null === $options->message ? $message : $options->message;

do {
try {
if ($condition() === $expectedResult) {
return;
}
} catch (\Throwable) {
} catch (\Throwable $error) {
// Waiting cannot make a locator that resolves to several
// elements resolve to one: fail now, as Playwright does.
if (str_contains($error->getMessage(), 'strict mode violation')) {
throw new AssertionException(self::describe($message, $error), expected: $expected, previous: $error);
}
}

if (hrtime(true) < $deadline) {
Expand All @@ -138,8 +145,17 @@ private function runAssertion(
}
}

$message = null === $options || null === $options->message ? $message : $options->message;

throw new AssertionException($message, actual: $actual, expected: $expected);
}

/**
* Appends Playwright's error to the failure message, without the terminal
* colors Playwright puts in its call log.
*/
private static function describe(string $message, \Throwable $error): string
{
$detail = trim((string) preg_replace('/\e\[[0-9;]*m/', '', $error->getMessage()));

return '' === $detail ? $message : $message."\n".$detail;
}
}
19 changes: 19 additions & 0 deletions tests/Integration/Assertions/LocatorAssertionsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
use PHPUnit\Framework\TestCase;
use Playwright\Assertions\AssertionOptions;
use Playwright\Assertions\Expect;
use Playwright\Assertions\Failure\AssertionException;
use Playwright\Assertions\LocatorAssertions;
use Playwright\Testing\PlaywrightTestCaseTrait;
use Playwright\Tests\Support\RouteServerTestTrait;
Expand Down Expand Up @@ -71,6 +72,24 @@ protected function tearDown(): void
$this->tearDownPlaywright();
}

#[Test]
public function itReportsALocatorThatResolvesToSeveralElements(): void
{
$this->page->setContent('<div class="breadcrumbs">Administration</div><h1>Administration</h1>');
$started = hrtime(true);

try {
Expect::locator($this->page->getByText('Administration'))->toBeVisible();
$this->fail('A locator that resolves to two elements must fail the assertion.');
} catch (AssertionException $exception) {
$this->assertLessThan(2000, (hrtime(true) - $started) / 1_000_000);
$this->assertStringStartsWith('Expected locator to be visible.', $exception->getMessage());
$this->assertStringContainsString('strict mode violation', $exception->getMessage());
$this->assertStringContainsString('resolved to 2 elements', $exception->getMessage());
$this->assertStringContainsString('<h1>Administration</h1>', $exception->getMessage());
}
}

#[Test]
public function itAssertsAttachedAndEditableLocators(): void
{
Expand Down
42 changes: 42 additions & 0 deletions tests/Unit/Assertions/Failure/AssertionExceptionTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?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.
*/

namespace Playwright\Tests\Unit\Assertions\Failure;

use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\TestCase;
use Playwright\Assertions\Failure\AssertionException;

#[CoversClass(AssertionException::class)]
final class AssertionExceptionTest extends TestCase
{
public function testKeepsTheActualAndExpectedValues(): void
{
$exception = new AssertionException('Expected locator to be visible.', actual: false, expected: true);

$this->assertSame('Expected locator to be visible.', $exception->getMessage());
$this->assertFalse($exception->actual);
$this->assertTrue($exception->expected);
$this->assertNull($exception->getPrevious());
}

public function testKeepsThePreviousError(): void
{
$previous = new \RuntimeException('strict mode violation');

$exception = new AssertionException('Expected locator to be visible.', previous: $previous);

$this->assertSame($previous, $exception->getPrevious());
}
}
43 changes: 43 additions & 0 deletions tests/Unit/Assertions/LocatorAssertionsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
use Playwright\Assertions\Internal\ScreenshotExpectation;
use Playwright\Assertions\LocatorAssertions;
use Playwright\Assertions\Options\ToHaveScreenshotOptions;
use Playwright\Exception\PlaywrightException;
use Playwright\Locator\Locator;
use Playwright\Locator\LocatorInterface;
use Playwright\Tracing\TracingInterface;
Expand Down Expand Up @@ -68,6 +69,48 @@ public function testToBeAttachedRetriesAfterAnEvaluationError(): void
);
}

public function testAStrictModeViolationFailsAtOnceWithThePlaywrightMessage(): void
{
$violation = new PlaywrightException("locator.isVisible: Error: strict mode violation: getByText('Administration') resolved to 2 elements:\n 1) <div>Administration</div>\n 2) <h1>Administration</h1>\n\nCall log:\n\e[2m - checking visibility\e[22m\n");
$locator = $this->createMock(LocatorInterface::class);
$locator->expects($this->once())->method('isVisible')->willThrowException($violation);

try {
(new LocatorAssertions($locator))->toBeVisible();
$this->fail('A strict mode violation must fail the assertion.');
} catch (AssertionException $exception) {
$this->assertStringStartsWith("Expected locator to be visible.\nlocator.isVisible: Error: strict mode violation", $exception->getMessage());
$this->assertStringContainsString('2) <h1>Administration</h1>', $exception->getMessage());
$this->assertStringEndsWith(' - checking visibility', $exception->getMessage());
$this->assertStringNotContainsString("\e", $exception->getMessage());
$this->assertSame($violation, $exception->getPrevious());
}
}

public function testAStrictModeViolationFailsANegatedAssertionAtOnce(): void
{
$locator = $this->createMock(LocatorInterface::class);
$locator->expects($this->once())
->method('isVisible')
->willThrowException(new PlaywrightException('strict mode violation: resolved to 2 elements'));

$this->expectException(AssertionException::class);
$this->expectExceptionMessage("Expected locator to be hidden.\nstrict mode violation: resolved to 2 elements");

(new LocatorAssertions($locator))->not()->toBeVisible();
}

public function testAStrictModeViolationKeepsACustomMessage(): void
{
$locator = $this->createMock(LocatorInterface::class);
$locator->method('isVisible')->willThrowException(new PlaywrightException('strict mode violation: resolved to 2 elements'));

$this->expectException(AssertionException::class);
$this->expectExceptionMessage("The heading is shown.\nstrict mode violation: resolved to 2 elements");

(new LocatorAssertions($locator))->toBeVisible(new AssertionOptions(message: 'The heading is shown.'));
}

public function testToBeEditable(): void
{
$locator = $this->createMock(LocatorInterface::class);
Expand Down
Loading