Skip to content

Testing

Code that drives a browser is easiest to trust when most of it is tested without one. PAM Browser is built around a small Transport interface, so you can replace the WebSocket with an in-memory fake, script the CDP responses, and assert on the commands your code sends. Keep a few integration tests that launch a real headless Chrome for the end-to-end path.

A transport only needs to send strings, return queued strings, and close:

tests/Support/FakeTransport.php
<?php
declare(strict_types=1);
namespace Tests\Support;
use Pam\Browser\Transport\Transport;
final class FakeTransport implements Transport
{
/** @var list<string> */
public array $sent = [];
/** @param list<string> $incoming CDP messages to return, in order */
public function __construct(private array $incoming = [])
{
}
public function send(string $payload): void
{
$this->sent[] = $payload;
}
public function receive(float $timeoutSeconds): ?string
{
return array_shift($this->incoming);
}
public function close(): void
{
}
}

Wrap it in a Connection and a Page, queue the responses Chrome would send, and exercise your code:

tests/Unit/TitleReaderTest.php
<?php
declare(strict_types=1);
namespace Tests\Unit;
use Pam\Browser\Connection;
use Pam\Browser\Page;
use PHPUnit\Framework\TestCase;
use Tests\Support\FakeTransport;
final class TitleReaderTest extends TestCase
{
public function testItReadsTheDocumentTitle(): void
{
$transport = new FakeTransport([
'{"id":1,"result":{"result":{"type":"string","value":"Acme"}}}',
]);
$page = new Page(new Connection($transport), 'target-1', 'session-1');
self::assertSame('Acme', $page->evaluate('document.title'));
$command = json_decode($transport->sent[0], true);
self::assertSame('Runtime.evaluate', $command['method']);
self::assertSame('session-1', $command['sessionId']);
}
}

Command ids start at 1 and increase by one per command on a connection, so your fake can answer them in order. To simulate an event, queue a message with a method and no id, for example {"method":"Page.loadEventFired","params":{},"sessionId":"session-1"}.

Launch a headless browser and use data: URLs so the test needs no network:

tests/Integration/BrowserSmokeTest.php
<?php
declare(strict_types=1);
namespace Tests\Integration;
use Pam\Browser\Browser;
use PHPUnit\Framework\TestCase;
final class BrowserSmokeTest extends TestCase
{
public function testItEvaluatesJavaScriptInARealPage(): void
{
$browser = Browser::launch();
try {
$page = $browser->newPage('data:text/html,<title>PAM Browser</title>');
self::assertSame('PAM Browser', $page->evaluate('document.title'));
} finally {
$browser->close();
}
}
}

Run integration tests through PAM so they use the same runtime as production:

Terminal window
pam vendor/bin/phpunit tests/Integration