Your first PHPUnit test
Move a browser flow into PHPUnit and assert a visible result.
Use PHPUnit when the browser flow should become part of your project test suite.
Create the test
Save this as tests/Browser/HomepageTest.php:
<?php
declare(strict_types=1);
namespace App\Tests\Browser;
use PHPUnit\Framework\Attributes\Group;
use PHPUnit\Framework\TestCase;
use Playwright\Testing\PlaywrightTestCaseTrait;
#[Group('browser')]
final class HomepageTest extends TestCase
{
use PlaywrightTestCaseTrait;
protected function setUp(): void
{
parent::setUp();
$this->setUpPlaywright();
}
protected function tearDown(): void
{
$this->tearDownPlaywright();
parent::tearDown();
}
public function testExamplePageHasHeading(): void
{
$this->page->goto('https://example.com');
$this->expect($this->page)->toHaveTitle('Example Domain');
$this->expect($this->page->getByRole('heading'))->toHaveText('Example Domain');
}
}
Run the test
vendor/bin/phpunit tests/Browser/HomepageTest.php
Expected result: PHPUnit reports a passing test.
What the trait gives you
PlaywrightTestCaseTrait creates browser objects for each test:
$this->pagefor browser actions;$this->contextfor the isolated browser session;$this->expect()for retrying browser assertions.
Keep browser tests clear
Start with one user-visible goal per test. Do not turn the first browser test into a full site tour.
Use the browser group to separate fast PHP tests from browser-backed tests:
vendor/bin/phpunit --exclude-group browser
vendor/bin/phpunit --group browser
If it fails
- If PHPUnit cannot find the trait, check that
playwright-php/playwrightis installed in the same project where PHPUnit runs. - If no tests are discovered, verify the file path, class suffix, namespace, and PHPUnit configuration.
- If Chromium cannot launch, install it with
vendor/bin/playwright-install chromium. - If the assertion times out, rerun the first script before debugging the test runner.
Next
Continue with Debug your first failure.
For a deeper testing setup, read Testing with PHPUnit or look up exact assertion methods in the API reference.