πŸ’‘ If you like this website, please share it with your friends and network! πŸš€
Back to All Questions
Question 65 of 100
Network
Advanced

How do you mock network requests in Playwright?

The Answer

Use `page.route()` to intercept requests by URL pattern, then call `route.fulfill()` to respond with mock data, `route.continue()` to pass through, or `route.abort()` to simulate failures.

Deep Dive Explanation

Route mocking makes tests deterministic β€” they don't depend on backend state or availability. This is essential for testing error states, loading states, and edge cases that are hard to reproduce with real data.

example.spec.ts
test('mocked API response', async ({ page }) => {
  // Intercept before navigation
  await page.route('**/api/products', async route => {
    await route.fulfill({
      status: 200,
      contentType: 'application/json',
      body: JSON.stringify([
        { id: 1, name: 'Mock Product', price: 29.99 }
      ]),
    });
  });

  await page.goto('/products');
  await expect(page.getByText('Mock Product')).toBeVisible();
});

// Simulate 500 error
await page.route('**/api/users', route => route.fulfill({ status: 500 }));

// Abort request (simulate network failure)
await page.route('**/api/data', route => route.abort());