diff --git a/src/Autoload.php b/src/Autoload.php index eddb8204..9e6c9fee 100644 --- a/src/Autoload.php +++ b/src/Autoload.php @@ -5,6 +5,8 @@ namespace Pest\Browser; use Pest\Browser\Playwright\Client; +use Pest\Browser\Playwright\Page; +use Pest\Browser\Playwright\Playwright; use Pest\Browser\Playwright\Server; use Pest\Plugin; use Pest\Plugins\Parallel; @@ -24,6 +26,23 @@ function visit(string $url): PendingTest } } +if (! function_exists('\Pest\Browser\page')) { + /** + * Visits the given URL, and starts a new browser test. + */ + function page(string $url = '/'): Page + { + Server::instance()->start(); + Client::instance()->connectTo(Server::instance()->url('?browser=chromium')); + + $browser = Playwright::chromium()->launch(); + $page = $browser->newPage(); + $page->goto($url); + + return $page; + } +} + register_shutdown_function(function (): void { if (Parallel::isEnabled() || ! Parallel::isWorker()) { Server::instance()->stop(); diff --git a/src/Browser.php b/src/Browser.php index 79a915cf..2d63e752 100644 --- a/src/Browser.php +++ b/src/Browser.php @@ -4,6 +4,8 @@ namespace Pest\Browser; +use Pest\Browser\Playwright\Page; + /** * @internal */ @@ -16,4 +18,12 @@ public function visit(string $url): PendingTest { return visit($url); } + + /** + * gets the page instance for given URL. + */ + public function page(string $url): Page + { + return page($url); + } } diff --git a/tests/Browser/Operations/AssertCheckedTest.php b/tests/Browser/Operations/AssertCheckedTest.php new file mode 100644 index 00000000..7c8560aa --- /dev/null +++ b/tests/Browser/Operations/AssertCheckedTest.php @@ -0,0 +1,19 @@ +page(playgroundUrl('/test/form-inputs')); + + expect($page->querySelector('input[name="checked-checkbox"]'))->toBeChecked(); + }); + + it('fails when checkbox is not checked', function () { + $page = $this->page(playgroundUrl('/test/form-inputs')); + + expect($page->querySelector('input[name="unchecked-checkbox"]'))->toBeChecked(); + })->throws(ExpectationFailedException::class); +}); diff --git a/tests/Pest.php b/tests/Pest.php index 73a8273f..91c5ee10 100644 --- a/tests/Pest.php +++ b/tests/Pest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +use Pest\Browser\Playwright\Element; +use Pest\Expectation; use Pest\TestSuite; pest() @@ -27,3 +29,12 @@ function playgroundUrl(string $path = '/'): string { return 'http://localhost:9357/'.mb_ltrim($path, '/'); } + +// todo: move this to Pest core +expect()->extend('toBeChecked', function (): Expectation { + + expect($this->value)->toBeInstanceOf(Element::class) + ->and($this->value->isChecked())->toBeTrue(); + + return $this; +});