|

Day 8: Network Interception — Mock APIs, Block Resources, Simulate Errors

This is Day 8 of the 21-Day Playwright with TypeScript Challenge. One lesson per day. Zero to production-ready in 3 weeks.

🎭 Want to master this with real projects? Join the Playwright Automation Mastery course at The Testing Academy.


page.route() intercepts every network request your app makes. Mock APIs, block analytics, simulate server errors — all without changing application code.

Contents

Mock API Responses

test('mock user API', async ({ page }) => {
  await page.route('**/api/users', route => {
    route.fulfill({
      status: 200,
      contentType: 'application/json',
      body: JSON.stringify([{ id: 1, name: 'Mock User' }])
    });
  });
  await page.goto('/users');
  await expect(page.getByText('Mock User')).toBeVisible();
});

Simulate Server Errors

test('handle 500 error gracefully', async ({ page }) => {
  await page.route('**/api/orders', route => {
    route.fulfill({ status: 500, body: 'Internal Server Error' });
  });
  await page.goto('/orders');
  await expect(page.getByText('Something went wrong')).toBeVisible();
  await expect(page.getByRole('button', { name: 'Retry' })).toBeVisible();
});

🚀 Level Up Your Playwright

From locators to CI pipelines — build a production-grade Playwright + TypeScript framework step by step.

Block Resources for Speed

test('fast page load without images', async ({ page }) => {
  await page.route('**/*.{png,jpg,gif,svg}', route => route.abort());
  await page.route('**/analytics/**', route => route.abort());
  await page.route('**google-analytics**', route => route.abort());
  await page.goto('/dashboard'); // 3x faster
});

Wait for Specific Responses

test('wait for search results', async ({ page }) => {
  const responsePromise = page.waitForResponse('**/api/search**');
  await page.goto('/search');
  await page.getByPlaceholder('Search').fill('playwright');
  await page.getByRole('button', { name: 'Search' }).click();
  const response = await responsePromise;
  expect(response.status()).toBe(200);
});

Tomorrow (Day 9): Authentication — storageState for skipping login.

🎓 Master Playwright End to End

Join hundreds of SDETs building real automation frameworks. Lifetime access, hands-on projects, and a job-ready portfolio.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.