Routing

Decide when to intercept a request, let it pass, modify it, or avoid mocking.

Routing lets a test control selected browser requests. Use it when the page must see a known response or when external traffic would make the test slow or unreliable.

In simple terms

Register the route before the action that triggers the request:

php
$page->route('**/api/shipping', function ($route): void {
    $route->fulfill([
        'status' => 503,
        'body' => json_encode(['error' => 'unavailable']),
    ]);
});

$page->goto('https://shop.example.test/checkout');

Observe vs route

If you only need to know that a request happened, wait for the request or response. If you need to decide what the page receives, route it.

Fulfill, abort, or continue

Need Use
Return a fake response fulfill
Block a request abort
Let it pass, possibly changed continue
Inspect only wait or event

Page route or context route

Use a page route when the mock belongs to one page.

Use a context route when every page in the context should see the same network rule, including popups or pages created later.

Keep route handlers explicit:

php
$context->route('**/api/shipping', static function ($route): void {
    $route->fulfill([
        'status' => 503,
        'contentType' => 'application/json',
        'body' => json_encode(['error' => 'unavailable']),
    ]);
});

After the mock, assert the product behavior:

php
expect($page->getByText('Shipping is temporarily unavailable'))->toBeVisible();

When not to use it

Do not mock your own application when a fixture or test database setup would be clearer. Mock the unstable edge, not the product you claim to test.

Debug missed routes

Check registration order, URL pattern, HTTP method, redirects, and whether the request comes from a frame or worker. If the route never fires, add a request log before changing the mock.

Go next