diff --git a/CHANGELOG.md b/CHANGELOG.md
index f23b2ca0..a63c350c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -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
diff --git a/src/Assertions/Failure/AssertionException.php b/src/Assertions/Failure/AssertionException.php
index 4b812ead..dc45f41d 100644
--- a/src/Assertions/Failure/AssertionException.php
+++ b/src/Assertions/Failure/AssertionException.php
@@ -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);
}
}
diff --git a/src/Assertions/Internal/AbstractAssertions.php b/src/Assertions/Internal/AbstractAssertions.php
index a56fde3b..4232f61f 100644
--- a/src/Assertions/Internal/AbstractAssertions.php
+++ b/src/Assertions/Internal/AbstractAssertions.php
@@ -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) {
@@ -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;
+ }
}
diff --git a/tests/Integration/Assertions/LocatorAssertionsTest.php b/tests/Integration/Assertions/LocatorAssertionsTest.php
index 5e1c0a6b..601c5ff0 100644
--- a/tests/Integration/Assertions/LocatorAssertionsTest.php
+++ b/tests/Integration/Assertions/LocatorAssertionsTest.php
@@ -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;
@@ -71,6 +72,24 @@ protected function tearDown(): void
$this->tearDownPlaywright();
}
+ #[Test]
+ public function itReportsALocatorThatResolvesToSeveralElements(): void
+ {
+ $this->page->setContent('
Administration
Administration
');
+ $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('Administration
', $exception->getMessage());
+ }
+ }
+
#[Test]
public function itAssertsAttachedAndEditableLocators(): void
{
diff --git a/tests/Unit/Assertions/Failure/AssertionExceptionTest.php b/tests/Unit/Assertions/Failure/AssertionExceptionTest.php
new file mode 100644
index 00000000..51e0c500
--- /dev/null
+++ b/tests/Unit/Assertions/Failure/AssertionExceptionTest.php
@@ -0,0 +1,42 @@
+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());
+ }
+}
diff --git a/tests/Unit/Assertions/LocatorAssertionsTest.php b/tests/Unit/Assertions/LocatorAssertionsTest.php
index 7acac2c0..c1fe786b 100644
--- a/tests/Unit/Assertions/LocatorAssertionsTest.php
+++ b/tests/Unit/Assertions/LocatorAssertionsTest.php
@@ -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;
@@ -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) Administration
\n 2) Administration
\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) Administration
', $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);