Skip to content

Commit

Permalink
Merge pull request #3 from saade/feat/to-have-title-regex
Browse files Browse the repository at this point in the history
feat: support both regex and non regex titles
  • Loading branch information
nunomaduro authored Feb 14, 2025
2 parents 637264e + e00b46c commit 0a81906
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 3 deletions.
5 changes: 4 additions & 1 deletion src/Operations/ToHaveTitle.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace Pest\Browser\Operations;

use Pest\Browser\Contracts\Operation;
use Pest\Browser\Support\Str;

/**
* @internal
Expand All @@ -22,6 +23,8 @@ public function __construct(

public function compile(): string
{
return sprintf('await expect(page).toHaveTitle(/%s/);', $this->title);
$title = Str::isRegex($this->title) ? $this->title : json_encode($this->title);

return sprintf('await expect(page).toHaveTitle(%s);', $title);
}
}
33 changes: 33 additions & 0 deletions src/Support/Str.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

declare(strict_types=1);

namespace Pest\Browser\Support;

/**
* @internal
*/
final class Str
{
/**
* Check if the given string is a regex.
*/
public static function isRegex(string $target): bool
{
if (strlen($target) < 2) {
return false;
}

// If the first and last characters are not the same, it's not a regex
if (($delimiter = substr($target, 0, 1)) !== substr($target, -1, 1)) {
return false;
}

// If the delimiter is alphanumeric, it's not a regex
if (! preg_match('/[^a-zA-Z0-9]/', $delimiter)) {

Check failure on line 27 in src/Support/Str.php

View workflow job for this annotation

GitHub Actions / Static Tests (prefer-lowest)

Only booleans are allowed in a negated boolean, int|false given.
return false;
}

return true;
}
}
8 changes: 6 additions & 2 deletions tests/Example.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,14 @@

it('may have a title at playwright', function () {
visit('https://playwright.dev/')
->toHaveTitle('Playwright');
->toHaveTitle('Fast and reliable end-to-end testing for modern web apps | Playwright')
->toHaveTitle('/testing/')
->toHaveTitle('/.*Playwright$/');
});

it('may have a title at laravel', function () {
visit('https://laravel.com')
->toHaveTitle('Laravel');
->toHaveTitle('Laravel - The PHP Framework For Web Artisans')
->toHaveTitle('/Framework/')
->toHaveTitle('/.*Artisans$/');
});

0 comments on commit 0a81906

Please sign in to comment.