Skip to content

Commit 0a81906

Browse files
authored
Merge pull request #3 from saade/feat/to-have-title-regex
feat: support both regex and non regex titles
2 parents 637264e + e00b46c commit 0a81906

File tree

3 files changed

+43
-3
lines changed

3 files changed

+43
-3
lines changed

src/Operations/ToHaveTitle.php

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
namespace Pest\Browser\Operations;
66

77
use Pest\Browser\Contracts\Operation;
8+
use Pest\Browser\Support\Str;
89

910
/**
1011
* @internal
@@ -22,6 +23,8 @@ public function __construct(
2223

2324
public function compile(): string
2425
{
25-
return sprintf('await expect(page).toHaveTitle(/%s/);', $this->title);
26+
$title = Str::isRegex($this->title) ? $this->title : json_encode($this->title);
27+
28+
return sprintf('await expect(page).toHaveTitle(%s);', $title);
2629
}
2730
}

src/Support/Str.php

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Pest\Browser\Support;
6+
7+
/**
8+
* @internal
9+
*/
10+
final class Str
11+
{
12+
/**
13+
* Check if the given string is a regex.
14+
*/
15+
public static function isRegex(string $target): bool
16+
{
17+
if (strlen($target) < 2) {
18+
return false;
19+
}
20+
21+
// If the first and last characters are not the same, it's not a regex
22+
if (($delimiter = substr($target, 0, 1)) !== substr($target, -1, 1)) {
23+
return false;
24+
}
25+
26+
// If the delimiter is alphanumeric, it's not a regex
27+
if (! preg_match('/[^a-zA-Z0-9]/', $delimiter)) {
28+
return false;
29+
}
30+
31+
return true;
32+
}
33+
}

tests/Example.php

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,14 @@
66

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

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

0 commit comments

Comments
 (0)